建造者模式
建造者模式和工厂模式的不同在于,工厂模式产生的对象都是模板化的,没有特性。建造者意在让用户创建个性特点的对象。java与模式一书中有个例子特别生动。女娲造人,但是人有四肢,头颅,身体等部件。女娲自己造任务太多,且达不到个性化。于是女娲将造人拆分为多个任务,分别交给不同的神。有的神专门做头颅,有的神专门做四肢。下面代码是精简版本。在Builder类中,创建一个Person对象,但是这个Person没有任何的属性。我们通过调用Builder对象的各个方法,来完善人的四肢,头颅。我们不传Head,那这个人就没有头。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 19:56 * @notify * @version 1.0 */ public class Person { private Head head; private Body body; private Limb limb; public Head getHead() { return head; } public void setHead(Head head) { this.head = head; } public Body getBody() { return body; } public void setBody(Body body) { this.body = body; } public Limb getLimb() { return limb; } public void setLimb(Limb limb) { this.limb = limb; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 20:00 * @notify * @version 1.0 */ public class Head { }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 20:00 * @notify * @version 1.0 */ public class Body { }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 20:01 * @notify * @version 1.0 */ public class Limb { }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 19:56 * @notify * @version 1.0 */ public class Builder { private Person person = new Person(); public Builder setHead(Head head) { person.setHead(head); return this; } public Builder setBody(Body body) { person.setBody(body); return this; } public Builder setLimb(Limb limb) { person.setLimb(limb); return this; } public Person build() { return person; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package builder_k;/* * @auther 顶风少年 * @mail dfsn19970313@foxmail.com * @date 2020-01-15 20:03 * @notify * @version 1.0 */ public class Main { public static void main(String[] args) { Builder builder = new Builder(); builder.setBody(new Body()); builder.setHead(new Head()); builder.setLimb(new Limb()); } }