设计模式之Builder模式
Builder模式
一个复杂对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示
场景:1 相同的方法,不同的执行顺序,产生不同的事件结果
2多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不同。
3产生类很复杂,产品类中的调用顺序产生不同的作用
4初始化对象很复杂,参数很多,且很多参数都是默认值。
Product Builder ConcreteBuilder Director
//抽象类 Product public abstract class Car { protected String LunTai; protected String fadongji; protected String pinpai; protected Car() {} public void setLunTai(String lunTai) { LunTai = lunTai; } public void setFadongji(String fadongji) { this.fadongji = fadongji; } public abstract void setPinpai(); @Override public String toString() { return "CAR:"+pinpai+":::::"+fadongji+"::::"+LunTai; } }
//具体product public class AUDI extends Car { protected AUDI(){} @Override public void setPinpai() { pinpai = "AUDI A8"; }; }
//抽象Builder public abstract class Builder { public abstract void buildLuntai(String luntai); public abstract void builddadongji(String fadongji); public abstract void buildpinpai(); public abstract Car createCar(); }
//具体Builder public class AudiBuilder extends Builder { private Car mcar = new AUDI(); @Override public void buildLuntai(String luntai) { mcar.setLunTai(luntai); } @Override public void builddadongji(String fadongji) { mcar.setFadongji(fadongji); } @Override public void buildpinpai() { mcar.setPinpai(); } @Override public Car createCar() { return mcar; } }
//Director 构建product public class Director { Builder mbuilder = null; public Director(Builder builder) { mbuilder = builder; } public void construct(String fadongji,String luntai){ mbuilder.builddadongji(fadongji); mbuilder.buildLuntai(luntai); mbuilder.buildpinpai(); } }
//TEST
public static void main(String[] args) { Builder builder = new AudiBuilder(); Director director = new Director(builder); director.construct("audi发动机", "Audi轮胎"); System.out.println(builder.createCar().toString()); }
通过具体Builder 构建具体product 对象,对外隐藏构建细节
实际开发中Director经常会省略:
Builder builder = new AudiBuilder(); builder.builddadongji("audi"); builder.buildLuntai("audi"); builder.createCar();
使其更加简单。