设计模式-建造者模式
传统建造者模式
Builder:定义创建的过程,一般是抽象类
ConcreteBuilder:真正的构建过程,重写Builder中的方法,相当于填充骨架
Director:指挥类,内部封装了构建的过程。作用是对外提供创建对象的接口,隐藏了创建对象的细节
代码:
//Product @Data class Person{ private String head; private String body; private String armL; private String armR; private String legL; private String legR; }
//builder //定义步骤,稳定过程 abstract class BuilderPersonStep { public abstract void buildHead(); public abstract void buildBody(); public abstract void buildArmL(); public abstract void buildArmR(); public abstract void buildLegL(); public abstract void buildLegR(); public abstract Person getPerson(); }
//ConcreteBuilder //创建胖小人 class fatPerson extends BuilderPersonStep { private Person person = new Person(); @Override public void buildHead() { person.setHead("胖小人的头"); } @Override public void buildBody() { person.setBody("胖小人的身体"); } @Override public void buildArmL() { person.setArmL("胖小人的左胳膊"); } @Override public void buildArmR() { person.setArmR("胖小人的右胳膊"); } @Override public void buildLegL() { person.setLegL("胖小人的左腿"); } @Override public void buildLegR() { person.setLegR("胖小人的右腿"); } @Override public Person getPerson() { return person; } }
//Director class BuilderDirector { private BuilderPersonStep builderStep; public BuilderDirector(BuilderPersonStep builderStep) { this.builderStep = builderStep; } public Person createPerson() { builderStep.buildHead(); builderStep.buildBody(); builderStep.buildArmL(); builderStep.buildArmR(); builderStep.buildLegL(); builderStep.buildLegR(); Person person = builderStep.getPerson(); return person; } }