工厂模式例子(一)

对工厂的抽象

 

public interface Builder {
	void buildMotor();
	void buildWheels();
	void paintColor();
	AbstractProduct getProduct();
}

 bus工厂

 

public class BusBuilder implements Builder {
	private String motor;
	private int wheels;
	private Color color;
	@Override
	public void buildMotor() {
		// TODO Auto-generated method stub
		this.motor = "Bus's motor";
	}
	@Override
	public void buildWheels() {
		// TODO Auto-generated method stub
		this.wheels = 8;
	}
	@Override
	public void paintColor() {
		// TODO Auto-generated method stub
		this.color = Color.green;
	}
	@Override
	public AbstractProduct getProduct() {
		AbstractProduct p = new Bus ();
		p.setColor(color);
		p.setMotor(motor);
		p.setWheels(wheels);
		return p;
	}
}

 Car工厂

 

public class CarBuilder implements  Builder{
	private String motor;
	private int wheels;
	private Color color;
	@Override
	public void buildMotor() {
		this.motor = "Car's motor";
	}
	@Override
	public void buildWheels() {
		this.wheels = 4;
	}
	@Override
	public void paintColor() {
		this.color = Color.black;
	}
	@Override
	public AbstractProduct getProduct() {
		AbstractProduct p = new Car ();
		p.setColor(color);
		p.setMotor(motor);
		p.setWheels(wheels);
		return p;
	}
}

 Trunk工厂

 

public class TruckBuilder implements Builder {
	private String motor;
	private int wheels;
	private Color color;
	@Override
	public void buildMotor() {
		this.motor = "Truck's motor";
	}
	@Override
	public void buildWheels() {
		this.wheels = 12;
	}
	@Override
	public void paintColor() {
		this.color = Color.gray;
	}
	@Override
	public AbstractProduct getProduct() {
		AbstractProduct p = new Truck ();
		p.setColor(color);
		p.setMotor(motor);
		p.setWheels(wheels);
		return p;
	}
}

 工厂控制

 

public class Director {
	private Builder builder;
	public Director(Builder builder){
		this.builder = builder ;
	}
	public void construct(){
		builder.buildMotor();
		builder.buildWheels();
		builder.paintColor();
	}
}

 

 

posted @ 2012-01-05 21:38  胖鹅  阅读(215)  评论(0编辑  收藏  举报