package com.lz.builder; /* * 组装者实现类,提供一个可以获取产品的公共方法 */ public class LzCarDirector implements CarDirector{ private CarBuilder cb; private Car car; public LzCarDirector(CarBuilder cb) { this.cb = cb; } @Override public Car CarDirector() { Car car = new Car(cb.BuilderDoor(), cb.BuilderEngine(), cb.BuilderTyre()); return car; } }
package com.lz.builder; /* * 建造者接口 */ public interface CarBuilder { Door BuilderDoor(); Engine BuilderEngine(); Tyre BuilderTyre(); }
package com.lz.builder; /* * 组装者接口 */ public interface CarDirector { Car CarDirector(); }
package com.lz.builder; /* * 建造者实现类 */ public class LzCarBuilder implements CarBuilder{ @Override public Door BuilderDoor() { return new Door("车门"); } @Override public Engine BuilderEngine() { return new Engine("发动机"); } @Override public Tyre BuilderTyre() { return new Tyre("轮胎"); } }
package com.lz.builder; /* * 产品类:有多个组件 * 将这些类的实现封装,用户只需要调用制造着和组装者就可以得到 * 实现类。 */ public class Car { private Door door; private Engine engine; private Tyre tyre; public Car() { } public Car(Door door, Engine engine, Tyre tyre) { super(); this.door = door; this.engine = engine; this.tyre = tyre; } public Door getDoor() { return door; } public void setDoor(Door door) { this.door = door; } public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } public Tyre getTyre() { return tyre; } public void setTyre(Tyre tyre) { this.tyre = tyre; } } class Door { private String name; public Door() { } public Door(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Engine { private String name; public Engine() { } public Engine(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Tyre { private String name; public Tyre() { } public Tyre(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.lz.builder; /* * 测试类 */ public class Test { public static void main(String[] args) { Car car = new LzCarDirector(new LzCarBuilder()).CarDirector(); System.out.println(car.getDoor().getName()); System.out.println(car.getEngine().getName()); System.out.println(car.getTyre().getName()); } }
时间: 2024-09-29 17:03:57