现在有一个需求:画一个人。
画人父类(规定了必须有的方法)
package BuilderPattern;
public abstract class PersonBuilder {
public abstract void buildHead();
public abstract void buildBody();
public abstract void buildArmLeft();
public abstract void buildArmRight();
public abstract void buildLegLeft();
public abstract void buildLegRight();
}
画人子类(一个瘦人,一个肥人,都实现画出四肢头部的方法)
class PersonThinBuilder extends PersonBuilder{
@Override
public void buildHead() {
// TODO Auto-generated method stub
System.out.println("瘦头");
}
@Override
public void buildBody() {
// TODO Auto-generated method stub
System.out.println("瘦身");
}
@Override
public void buildArmLeft() {
// TODO Auto-generated method stub
System.out.println("瘦左手");
}
@Override
public void buildArmRight() {
// TODO Auto-generated method stub
System.out.println("瘦右手");
}
@Override
public void buildLegLeft() {
// TODO Auto-generated method stub
System.out.println("瘦左脚");
}
@Override
public void buildLegRight() {
// TODO Auto-generated method stub
System.out.println("瘦右脚");
}
}
class PersonBigBuilder extends PersonBuilder{
@Override
public void buildHead() {
// TODO Auto-generated method stub
System.out.println("肥头");
}
@Override
public void buildBody() {
// TODO Auto-generated method stub
System.out.println("肥身");
}
@Override
public void buildArmLeft() {
// TODO Auto-generated method stub
System.out.println("肥左手");
}
@Override
public void buildArmRight() {
// TODO Auto-generated method stub
System.out.println("肥右手");
}
@Override
public void buildLegLeft() {
// TODO Auto-generated method stub
System.out.println("肥左脚");
}
@Override
public void buildLegRight() {
// TODO Auto-generated method stub
System.out.println("肥右脚");
}
}
指挥家(封装画画的所有方法,避免却少肢体)
package BuilderPattern;
public class PersonDirector {
PersonBuilder pb;
public PersonDirector(PersonBuilder pb) {
// TODO Auto-generated constructor stub
this.pb = pb;
}
public void createPerson(){
pb.buildHead();
pb.buildBody();
pb.buildArmLeft();
pb.buildArmRight();
pb.buildLegLeft();
pb.buildLegRight();
}
}
界面类(实例化指挥家的时候需要传入你需要画肥人还是瘦人作为参数,然后调用封装方法直接画出一个人出来。)
package BuilderPattern;
public class Main {
public void printFrame(){
PersonThinBuilder ptb = new PersonThinBuilder();
PersonBigBuilder pbb = new PersonBigBuilder();
PersonDirector pdthin ;
PersonDirector pdbig ;
System.out.println("*********建设者模式*********");
System.out.println("画一个瘦仔");
pdthin = new PersonDirector(ptb);
pdthin.createPerson();
System.out.println("画一个肥仔");
pdbig = new PersonDirector(pbb);
pdbig.createPerson();
}
public static void main(String[] args) {
Main main = new Main();
main.printFrame();
}
}
好处:将产品内部的表象和生产过程分割开来,用户只需要指定类型就可以得到他们,具体构建细节不存在。
使用:通常用于那些构建顺序稳定,但对象内部的构建会有复杂变化,