创建者模式 builder
package mode.bulider; /** * * 首先是汽车,组成零件有:玻璃、轮胎、发动机;他们都是抽象的概念,所以用抽象类来创建 * * */ public class Car { Glass glass; Wheel wheel; Engine engine; }
package mode.bulider; /** * * 抽象的玻璃 * * */ public abstract class Glass { }
package mode.bulider; public class AmericanGlass extends Glass { public String toString() { return "\"American Glass\""; } }
package mode.bulider; public class JapaneseGlass extends Glass { public String toString() { return "\"Japanese Glass\""; } }
package mode.bulider; /** * * 抽象的轮胎 * * */ public abstract class Wheel { }
package mode.bulider; public class AmericanWheel extends Wheel { public String toString() { return "\"American Wheel\""; } }
package mode.bulider; public class JapaneseWheel extends Wheel { public String toString() { return "\"Janpanes Wheel\""; } }
package mode.bulider; /** * * 抽象的发动机 * * */ public abstract class Engine { }
package mode.bulider; public class ChineseEngine extends Engine { public String toString() { return "\"Chinese Engine\""; } }
package mode.bulider; public class FranceEngine extends Engine { public String toString() { return "\"France Engine\""; } }
package mode.bulider; /** * * 创建一个汽车的构造器 * * */ public interface CarBuilder { public void buildGlass(); public void buildWheel(); public void buildEngine(); public Car getProduct(); }
下面是两个具体的实现
package mode.bulider; public class CarABuilder implements CarBuilder { private Car product = null; public CarABuilder() { product = new Car(); } @Override public void buildGlass() { product.glass = new AmericanGlass(); } @Override public void buildWheel() { product.wheel = new AmericanWheel(); } @Override public void buildEngine() { product.engine = new ChineseEngine(); } @Override public Car getProduct() { buildGlass(); buildEngine(); buildWheel(); return product; } }
package mode.bulider; public class CarBBuilder implements CarBuilder { private Car product; public CarBBuilder() { product = new Car(); } @Override public void buildGlass() { product.glass = new JapaneseGlass(); } @Override public void buildWheel() { product.wheel = new JapaneseWheel(); } @Override public void buildEngine() { product.engine = new FranceEngine(); } @Override public Car getProduct() { buildEngine(); buildGlass(); buildWheel(); return product; } }
package mode.bulider; /** * * 构造器引导措施 * * */ public class Director { private CarBuilder builder; public Director(CarBuilder builder) { this.builder = builder; } public Car Construct() { return builder.getProduct(); } }
测试
package mode.bulider; public class Test { public static void main(String[] args) { Director d1 = new Director(new CarABuilder()); Director d2 = new Director(new CarBBuilder()); d1.Construct(); d2.Construct(); } }