建造者模式
讲一个复杂构建与他的表示分离,使得同样的构建可以创建不同的表示。
优点
- 封装性:客户端不必知道产品内部组成的细节。
- 建造者独立,容易扩展。例子中,惠普和苹果建造者互相独立。
- 便于控制细节风险。
应用场景
- 需要生成的产品对象有复杂的内部结构,这些产品对象具备共性。
- 隔离复杂对象的创建和使用,并使得形同的创建过程可以创建不同的产品。
- 相同方法,不同的执行顺序。
代码
新建一个产品类
1 | public class Computer { |
建造者接口:
1 | public interface IBuildComputer { |
具体建造者:
1 | public class HPComputer implements IBuildComputer { |
Director导演类,负责安排已有模块顺序:
1 | public class Director { |
测试
1 | public class Main { |
结果
1 | Computer{CPU='惠普cpu', capacity='560G', ram='16G', system='windows10'} |