建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。
步骤接口
/**
* @Author: chuan.bai
* @Description 泡茶接口
* @Date: Created on 16:45 2021/3/26
* @Modified By:
*/
public interface MakeTeaService {
//准备茶叶
void prepareTeaLeaf();
//放入杯中
void putInTheCup();
//导入热水
void pourHotWater();
}
步骤的具体实现
/**
* @Author: chuan.bai
* @Description 泡绿茶 具体步骤
* @Date: Created on 16:49 2021/3/26
* @Modified By:
*/
public class MakeGreenTea implements MakeTeaService{
@Override
public void prepareTeaLeaf() {
System.out.println("准备绿茶");
}
@Override
public void putInTheCup() {
System.out.println("把绿茶放入杯中");
}
@Override
public void pourHotWater() {
System.out.println("把热水倒入杯中");
}
}
/**
* @Author: chuan.bai
* @Description 泡红茶 具体步骤
* @Date: Created on 16:49 2021/3/26
* @Modified By:
*/
public class MakeRedTea implements MakeTeaService{
@Override
public void prepareTeaLeaf() {
System.out.println("准备红茶");
}
@Override
public void putInTheCup() {
System.out.println("把红茶放入杯中");
}
@Override
public void pourHotWater() {
System.out.println("把热水倒入杯中");
}
}
泡茶建造者
/**
* @Author: chuan.bai
* @Description 泡茶建造借口
* @Date: Created on 16:52 2021/3/26
* @Modified By:
*/
public interface MakeTeaBuilder {
//泡茶接口
void makeTea();
}
泡红茶绿茶的建造者
/**
* @Author: chuan.bai
* @Description 泡红茶的建造者
* @Date: Created on 16:55 2021/3/26
* @Modified By:
*/
public class MakeRedTeaBuilder implements MakeTeaBuilder {
MakeRedTea makeRedTea = new MakeRedTea();
@Override
public void makeTea() {
makeRedTea.prepareTeaLeaf();
makeRedTea.putInTheCup();
makeRedTea.pourHotWater();
}
}
/**
* @Author: chuan.bai
* @Description 泡绿茶的建造者
* @Date: Created on 16:55 2021/3/26
* @Modified By:
*/
public class MakeGreenTeaBuilder implements MakeTeaBuilder {
MakeGreenTea makeGreenTea = new MakeGreenTea();
@Override
public void makeTea() {
makeGreenTea.prepareTeaLeaf();
makeGreenTea.putInTheCup();
makeGreenTea.pourHotWater();
}
}
生产方
/**
* @Author: chuan.bai
* @Description
* @Date: Created on 16:57 2021/3/26
* @Modified By:
*/
public class Director {
public static void main(String[] args) {
/**
* 泡绿茶
*/
MakeGreenTeaBuilder makeGreenTeaBuilder =new MakeGreenTeaBuilder();
makeGreenTeaBuilder.makeTea();
/**
* 泡红茶
*/
MakeRedTeaBuilder makeRedTeaBuilder = new MakeRedTeaBuilder();
makeRedTeaBuilder.makeTea();
}
}
输出结果
准备绿茶
把绿茶放入杯中
把热水倒入杯中
准备红茶
把红茶放入杯中
把热水倒入杯中
Process finished with exit code 0