标签:分离 cte set 角色 person 系统 场景 over pre
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造者模式通常有4个角色
Person抽象类:定义模板方法及基本方法
public abstract class AbstractPerson {
private boolean canSwim = true;
public void setCanSwim(boolean canSwim) {
this.canSwim = canSwim;
}
protected abstract void walk();
protected abstract void run();
protected abstract void swim();
public final void exercises() {
this.walk();
if (this.canSwim()) {
this.swim();
}
this.run();
}
protected boolean canSwim() {
return canSwim;
}
}
Person实现类:实现基本方法,通常实现模板方法模式,有模板方法及基本方法
public class PersonA extends AbstractPerson {
@Override
protected void walk() {
System.out.println("person a walk");
}
@Override
protected void run() {
System.out.println("person a run");
}
@Override
protected void swim() {
System.out.println("person a swim");
}
}
public class PersonB extends AbstractPerson {
@Override
protected void walk() {
System.out.println("person b walk");
}
@Override
protected void run() {
System.out.println("person b run");
}
@Override
protected void swim() {
System.out.println("person b swim");
}
}
Builder抽象建造者:规范Person行为,设置Person的组建,一般由子类实现
public abstract class AbstractBuilder {
public abstract void setPart();
public abstract AbstractPerson builderPerson();
}
Builder实现类:具体的建造者
public class PersonABuilder extends AbstractBuilder {
private AbstractPerson person = new PersonA();
@Override
public void setPart() {
person.setCanSwim(true);
}
@Override
public AbstractPerson builderPerson() {
return person;
}
}
public class PersonBBuilder extends AbstractBuilder {
private AbstractPerson person = new PersonB();
@Override
public void setPart() {
person.setCanSwim(false);
}
@Override
public AbstractPerson builderPerson() {
return person;
}
}
Director导演类
public class Director {
private AbstractBuilder personABuilder = new PersonABuilder();
private AbstractBuilder personBBuilder = new PersonBBuilder();
public PersonA getPersonA() {
this.personABuilder.setPart();
return (PersonA) this.personABuilder.builderPerson();
}
public PersonB getPersonB() {
this.personBBuilder.setPart();
return (PersonB) this.personBBuilder.builderPerson();
}
}
注意:建造者模式关注的是产品的类型(setPart函数)与产品装配的顺序(exercises函数)
标签:分离 cte set 角色 person 系统 场景 over pre
原文地址:https://www.cnblogs.com/jeff-chang/p/13472873.html