工厂模式例子(二)
抽象出产品
public abstract class AbstractProduct { private String motor; private int wheels; private Color color; public String getMotor() { return motor; } public void setMotor(String motor) { this.motor = motor; } public int getWheels() { return wheels; } public void setWheels(int wheels) { this.wheels = wheels; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public abstract void canLoad(); public void print(){ System.out.println(motor + "; wheels:" + wheels + "; color:" + color); canLoad(); } }
具体的产品BUS
public class Bus extends AbstractProduct { public void canLoad() { System.out.println("Bus: can load at most 40 passengers"); } }
具体的产品Car
public class Car extends AbstractProduct{ public void canLoad() { System.out.println("Car: can load 4 passengers"); } }
具体的产品Truck
public class Truck extends AbstractProduct{ public void canLoad() { System.out.println("Truck: can load much goods"); } }
开始生产产品
public class BuilderTest { public static void main(String[] a){ //创造不同的Builder Builder builder1 = new CarBuilder(); Builder builder2 = new BusBuilder(); Builder builder3 = new TruckBuilder(); //Director使用不同的Builder,最终得到不同的产品 Director director = new Director(builder3); director.construct(); AbstractProduct product = builder3.getProduct(); product.print(); } }
回忆过去,珍惜现在,放眼未来