- 建造者模式代码
- 家庭实体类
/**
* @Author jijl
* @Description: 家庭实体类
* @Date 17:34 2019/1/17
**/
public class Family {
private String father;
private String mother;
private String brother;
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String getMother() {
return mother;
}
public void setMother(String mother) {
this.mother = mother;
}
public String getBrother() {
return brother;
}
public void setBrother(String brother) {
this.brother = brother;
}
}
- 定义一个家庭成员标准的接口
/**
* @Author jijl
* @Description: 建造家庭类接口
* @Date 17:36 2019/1/17
**/
public interface IBuildFamily {
void buildFather();
void buildMother();
void buildBrother();
Family createFamily();
}
- 小明一家人
/**
* @Author jijl
* @Description: 小明家
* @Date 17:51 2019/1/17
**/
public class XmFamilyBuilderimpl implements IBuildFamily {
Family family;
public XmFamilyBuilderimpl() {
family = new Family();
}
@Override
public void buildFather() {
family.setFather("1.70米的爸爸");
}
@Override
public void buildMother() {
family.setMother("1.65米的妈妈");
}
@Override
public void buildBrother() {
family.setBrother("1.80米的弟弟");
}
@Override
public Family createFamily() {
return family;
}
}
- 大明一家人
/**
* @Author jijl
* @Description: 大明家
* @Date 17:50 2019/1/17
**/
public class DmFamilyBuilderimpl implements IBuildFamily {
Family family;
public DmFamilyBuilderimpl() {
family = new Family();
}
@Override
public void buildFather() {
family.setFather("2米的爸爸");
}
@Override
public void buildMother() {
family.setMother("1.8米的妈妈");
}
@Override
public void buildBrother() {
family.setBrother("2.20米的弟弟");
}
@Override
public Family createFamily() {
return family;
}
}
- 建造者模式的精髓,director
public class Director {
public Family createFamilyByDirecotr(IBuildFamily bf){
bf.buildBrother();
bf.buildFather();
bf.buildMother();
return bf.createFamily();
}
}
- 测试类
public class BuilderTest {
public static void main(String[] args) {
Director director = new Director();
Family xmFamily = director.createFamilyByDirecotr(new XmFamilyBuilderimpl());
System.out.println("小明家---------");
System.out.println(xmFamily.getFather());
System.out.println(xmFamily.getMother());
System.out.println(xmFamily.getBrother());
Family dmFamily = director.createFamilyByDirecotr(new DmFamilyBuilderimpl());
System.out.println("大明家---------");
System.out.println(dmFamily.getFather());
System.out.println(dmFamily.getMother());
System.out.println(dmFamily.getBrother());
}
}
输出结果
小明家---------
1.70米的爸爸
1.65米的妈妈
1.80米的弟弟
大明家---------
2米的爸爸
1.8米的妈妈
2.20米的弟弟
会发现,在最后的BuilderTest类中,我们其实根本就不会知道具体是怎么创建家庭的,因为这个过程让director给代劳了。DmFamilyBuilderimpl 和 XmFamilyBuilderimpl类中才是真正的创造方法。director其实只是执行了这个过程。这样子,达到了分离模块的功能。创造家庭的过程,启动创造的过程,和最后选择哪个家庭来造。都分的清清楚楚。就有了一些模块化的感觉,这样维护和扩展都是很方便的。