建造者模式

Builder 模式很重要的两个概念就是导演类和Builder类。
Builder类只负责每个独立的部分的构建,而导演类则统筹规划,一手操控这大局。

p.s: 每个人都向往幸福的生活, 但程序员苦啊。。。 不过还好程序员什么都能造。 少废话, 先上客户端代码
public class Client {
	public static void main(String[] args) {
		AbstractBuilder builder = new PerfectLifeBuilder();
		Director director = new Director(builder);

		director.construct();

		PerfectLife myLife = builder.getResult();

		System.out.println("This is my life:");
		System.out.println(myLife.getHouse());
		System.out.println(myLife.getCar());
		System.out.println(myLife.getWife());
	}
}


执行结果:
引用
This is my life:
我有房子啦
车子也有啦
我们程序员无所不能,老婆都能造,咋样?


幸福生活的定义
/**
 * 别期望的太多, 有房有车有老婆就已经够perfect了
 */
public class PerfectLife {
	private String house;
	private String car;
	private String wife;

	public PerfectLife(String house, String car, String wife) {
		this.house = house;
		this.car = car;
		this.wife = wife;
	}

	// gets & sets
}


再看看AbstractBuilder
public abstract class AbstractBuilder {

	public String house, car, wife;

	public abstract void buildHouse();

	public abstract void buildCar();

	public abstract void buildWife();

	public PerfectLife getResult() {
		return new PerfectLife(this.house, this.car, this.wife);
	}
}


然后是具体的Builder
public class PerfectLifeBuilder extends AbstractBuilder {

	public void buildHouse() {
		this.house = "我有房子啦";
	}

	public void buildCar() {
		this.car = "车子也有啦";
	}

	public void buildWife() {
		this.wife = "我们程序员无所不能,老婆都能造,咋样?";
	}
}


万事俱备, 只欠导演了
public class Director {
	private AbstractBuilder builder;

	public Director(AbstractBuilder builder) {
		this.builder = builder;
	}

	public void construct() {
		builder.buildHouse();
		builder.buildCar();
		builder.buildWife();
	}
}


你可能感兴趣的:(java,生活)