建造者模式
Posted kankankankankan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式相关的知识,希望对你有一定的参考价值。
定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。将建造复杂对象的过程和组成对象的部件解耦。
包含如下几种角色:
Builder:抽象建造者(Builder
)
ConcreteBuilder:具体建造者(CommonBuilder
、SuperBuilder
)
Director:指挥者(Director
)
Product:产品角色(Role
)
1、定义角色类相关属性
/** * 定义角色类相关属性 * @author Tim * */ public class Role { private String head; private String face; private String body; public String getHead() { return head; } public void setHead(String head) { this.head = head; } public String getFace() { return face; } public void setFace(String face) { this.face = face; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return this.head + "\t" + this.face + "\t" + this.body; } }
2、定义建造者
/** * 定义抽象构建方法 * @author Tim * */ public abstract class Builder { Role role = new Role(); public abstract void buildHead(); public abstract void buildFace(); public abstract void buildBody(); public Role getResult() { return role; } }
3、具体建造者二种实现
/** * 实现抽象构造类_1 * @author Tim * */ public class CommonBuilder extends Builder{ private Role role = new Role(); @Override public void buildHead() { role.setHead("common head building..."); } @Override public void buildFace() { role.setFace("common face building..."); } @Override public void buildBody() { role.setBody("common body building..."); } @Override public Role getResult() { return role; } }
/** * 抽象构建类实现_2 * @author Tim * */ public class SuperBuilder extends Builder{ private Role role = new Role(); @Override public void buildHead() { role.setHead("super head building..."); } @Override public void buildFace() { role.setFace("super face building..."); } @Override public void buildBody() { role.setBody("super body building..."); } @Override public Role getResult() { return role; } }
4、指挥者
/** * 定义构建过程方法 * @author Tim * */ public class Director { public void build(Builder builder) { builder.buildHead(); builder.buildFace(); builder.buildBody(); } }
5、测试
/** * 构建模式测试类 * @author Tim * */ public class BuilderMain { public static void main(String[] args) { Builder builder = new CommonBuilder(); Director director = new Director(); director.build(builder); System.out.println(builder.getResult()); } }
以上是关于建造者模式的主要内容,如果未能解决你的问题,请参考以下文章