建造者模式(Builder):将一个复杂对象的构造与它的表示分离,使得同样的构建过程可以创建不同的表示。
简单理解就是本质一样的,但是表现出来的样子不一样。就好比如人,有高的,矮的,瘦的,胖的,但是不管外面的表现是什么样子的,唯一肯定一样的就是都是人
建造者模式就是为了工作流程所有的步骤都不漏掉。
UML图
例子:建造小人(想不出好的例子,就采用了大话设计模式里面的例子)
代码结构图
代码展示
PersonBuilder():接口
package com.magggie.Builder; public interface PersonBuilder { void BuildHead(); void BuildBody(); void BuildArmLeft(); void BuildArmRight(); void BuildLegLeft(); void BuildLegRight(); }
PersonFatBuilder():
package com.magggie.Builder; public class PersonFatBuilder implements PersonBuilder{ @Override public void BuildHead() { System.out.println("Fat head"); } @Override public void BuildBody() { System.out.println("Fat body"); } @Override public void BuildArmLeft() { System.out.println("Fat Arm left"); } @Override public void BuildArmRight() { System.out.println("Fat arm right"); } @Override public void BuildLegLeft() { System.out.println("Fat leg left"); } @Override public void BuildLegRight() { System.out.println("Fat leg right"); } }
PersonThinBuilder
package com.magggie.Builder; public class PersonThinBuilder implements PersonBuilder { @Override public void BuildHead() { System.out.println("Thin head"); } @Override public void BuildBody() { System.out.println("Thin Body"); } @Override public void BuildArmLeft() { System.out.println("Thin Arm Left"); } @Override public void BuildArmRight() { System.out.println("Thin Arm Right"); } @Override public void BuildLegLeft() { System.out.println("Thin Leg Left"); } @Override public void BuildLegRight() { System.out.println("Thin Leg Right"); } }
PersonDirector
package com.magggie.Builder; public class PersonDirector { private PersonBuilder pb;//聚合关系体现在这 public PersonDirector(PersonBuilder pb) { super(); this.pb = pb; } public void createPerson() { pb.BuildHead(); pb.BuildBody(); pb.BuildArmLeft(); pb.BuildArmRight(); pb.BuildLegLeft(); pb.BuildLegRight(); } }
客户端调用
package com.magggie.Builder; public class Client { public static void main(String[] args) { PersonThinBuilder pdThin = new PersonThinBuilder(); PersonDirector makeThin = new PersonDirector(pdThin); makeThin.createPerson(); PersonFatBuilder pdFat = new PersonFatBuilder(); PersonDirector makeFat = new PersonDirector(pdFat); makeFat.createPerson(); } }
输出
Thin head
Thin Body
Thin Arm Left
Thin Arm Right
Thin Leg Left
Thin Leg Right
Fat head
Fat body
Fat Arm left
Fat arm right
Fat leg left
Fat leg right
建造者模式的要点就是在于指挥者Director持有Builder,可指挥建造实现Builder下的任何Product,这里涉及到多态
Builder把所有的流程都加入,只要实现它就一定要重写这些流程方法,因此不可能会出现某一个流程漏掉。