设计模式——生成器模式
Posted 神恰恰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式——生成器模式相关的知识,希望对你有一定的参考价值。
这次来看下生成器模式,先来看下类图:
那么来说下特点吧:
- 将一个复杂对象的创建过程封装起来
- 允许对象通过多个步骤来创建,并且可以改变过程
- 实现可以被替换
- 隐藏了内部实现
来看下代码吧:
public abstract class AbstractCarBuilder { public Car car = new Car(); public abstract AbstractCarBuilder builderName(String name); public abstract AbstractCarBuilder builderTire(String Tire); public abstract AbstractCarBuilder builderEngine(String Engine); public abstract AbstractCarBuilder builderChassis(String Chassis); public abstract Car getCar(); }
public class Car { private String name; private String tire; private String engine; private String chassis; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTire() { return tire; } public void setTire(String tire) { this.tire = tire; } public String getEngine() { return engine; } public void setEngine(String engine) { this.engine = engine; } public String getChassis() { return chassis; } public void setChassis(String chassis) { this.chassis = chassis; } @Override public String toString() { String car = name + "," + tire + "," + engine + "," + chassis; return car; } }
public class CarBuilder extends AbstractCarBuilder { @Override public AbstractCarBuilder builderName(String name) { car.setName(name); return this; } @Override public AbstractCarBuilder builderTire(String Tire) { car.setTire(Tire); return this; } @Override public AbstractCarBuilder builderEngine(String Engine) { car.setEngine(Engine); return this; } @Override public AbstractCarBuilder builderChassis(String Chassis) { car.setChassis(Chassis); return this; } @Override public Car getCar() { return car; } }
以上是关于设计模式——生成器模式的主要内容,如果未能解决你的问题,请参考以下文章
Azure 机器人微软Azure Bot 编辑器系列 : 机器人/用户提问回答模式,机器人从API获取响应并组织答案 (The Bot Framework Composer tutorial(代码片段
csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us