建造者模式是对象创建型设计模式之一,他主要用于构造复杂对象,而这个复杂对象则可以由多组不同的产品族构成,其结构原理图如下:
其中关键部件有两个
1. Builder
Builder定义了生产复杂对象的组件的抽象接口(BuildPart)和获取这个复杂对象的方法(GetResult),但他自己本身并不装配对象,简言之Builder是生成复杂对象部件的接口提供者
2. Director
Director定义了装配复杂对象的接口,它使用Builder提供的生产复杂对象组件的方法来生成组件,并将其装配起来,最后调用GetResult返回该复杂对象
例子:
Component
Body组件族
public abstract class Body { public abstract void showBody(); } public class LongBody extends Body { @Override public void showBody() { System.out.println("I have a long body"); } } public class ShortBody extends Body { @Override public void showBody() { System.out.println("I hava a short body"); } }
Head组件族
public abstract class Head { public abstract void showHead(); } public class BigHead extends Head { @Override public void showHead() { System.out.println("I have a very very big head!"); } } public class SmallHead extends Head { @Override public void showHead() { System.out.println("I only have a really small head!"); } }
复杂对象Man
public class Man { private Head head; private Body body; public void setHead(Head head) { this.head = head; } public void setBody(Body body) { this.body = body; } public void showMe() { head.showHead(); body.showBody(); } }
Builder
public abstract class ManBuilder { protected Man man; public Man getMan() { return man; } public void buildMan() { man = new Man(); } public abstract void buildHead(); public abstract void buildBody(); } public class BigManBuilder extends ManBuilder { @Override public void buildHead() { man.setHead(new BigHead()); } @Override public void buildBody() { man.setBody(new LongBody()); } } public class SmallManBuilder extends ManBuilder { @Override public void buildHead() { man.setHead(new SmallHead()); } @Override public void buildBody() { man.setBody(new ShortBody()); } } public class AbnormalManBuilder extends ManBuilder { @Override public void buildHead() { man.setHead(new BigHead()); } @Override public void buildBody() { man.setBody(new ShortBody()); } }
Director
public class ManDirector { public Man createMan(ManBuilder builder) { builder.buildMan(); builder.buildHead(); builder.buildBody(); return builder.getMan(); } }
客户端
public class Client { public static void main(String[] args) { ManBuilder bigManBuilder = new BigManBuilder(); ManBuilder smallManBuilder = new SmallManBuilder(); ManBuilder abnormalManBuilder = new AbnormalManBuilder(); ManDirector manDirector = new ManDirector(); Man bigMan = manDirector.createMan(bigManBuilder); Man smallMan = manDirector.createMan(smallManBuilder); Man abnormalMan = manDirector.createMan(abnormalManBuilder); bigMan.showMe(); smallMan.showMe(); abnormalMan.showMe(); } }
优势:
1. 隐藏产品的内部结构(Builder)和其装配过程(Director),在改变产品的内部表示时只需要创建新的Builder(例如使用不同的Head和Body构造Man)
2. 解耦复杂对象的构建过程(Director)和表示方式(Builder),使得可以生成不同的构造过程(Director),并在不同的Director复用相同的Builder
3. 对构建过程进行精细控制,可以在Director内对构建构成进行控制
4. 定义Director 固定产品的构造过程,使产品的构造不会出错(例如漏掉某些构造部件的过程)