將一個複雜對象的構建與它的表示分離,使得一樣的構建過程能夠建立不一樣的表示。java
建造者模式一般有4個角色ide
Person抽象類:定義模板方法及基本方法函數
public abstract class AbstractPerson { private boolean canSwim = true; public void setCanSwim(boolean canSwim) { this.canSwim = canSwim; } protected abstract void walk(); protected abstract void run(); protected abstract void swim(); public final void exercises() { this.walk(); if (this.canSwim()) { this.swim(); } this.run(); } protected boolean canSwim() { return canSwim; } }
Person實現類:實現基本方法,一般實現模板方法模式,有模板方法及基本方法ui
public class PersonA extends AbstractPerson { @Override protected void walk() { System.out.println("person a walk"); } @Override protected void run() { System.out.println("person a run"); } @Override protected void swim() { System.out.println("person a swim"); } } public class PersonB extends AbstractPerson { @Override protected void walk() { System.out.println("person b walk"); } @Override protected void run() { System.out.println("person b run"); } @Override protected void swim() { System.out.println("person b swim"); } }
Builder抽象建造者:規範Person行爲,設置Person的組建,通常由子類實現this
public abstract class AbstractBuilder { public abstract void setPart(); public abstract AbstractPerson builderPerson(); }
Builder實現類:具體的建造者code
public class PersonABuilder extends AbstractBuilder { private AbstractPerson person = new PersonA(); @Override public void setPart() { person.setCanSwim(true); } @Override public AbstractPerson builderPerson() { return person; } } public class PersonBBuilder extends AbstractBuilder { private AbstractPerson person = new PersonB(); @Override public void setPart() { person.setCanSwim(false); } @Override public AbstractPerson builderPerson() { return person; } }
Director導演類對象
public class Director { private AbstractBuilder personABuilder = new PersonABuilder(); private AbstractBuilder personBBuilder = new PersonBBuilder(); public PersonA getPersonA() { this.personABuilder.setPart(); return (PersonA) this.personABuilder.builderPerson(); } public PersonB getPersonB() { this.personBBuilder.setPart(); return (PersonB) this.personBBuilder.builderPerson(); } }
注意:建造者模式關注的是產品的類型(setPart函數)與產品裝配的順序(exercises函數)ci