构建者模式

概念:

即采用构建者和构建工具两个角色来封装复杂对象及其子对象的创建过程(子对象一般都具有多边性)。

要点:

1、 创建构建工具(接口+实现类),封装对象和子对象创建过程

2、创建构建者,封装创建工具的创建细节,供消费者使用

实例:

1、pojo类

/**
 * 汽车实体类
 * 简单起见,每个汽车封装了两个复杂对象引擎和轮子
 * 引擎和轮子都具有复杂性和多变性两个特点
 * 
 * @author ypqiao
 *
 */
public class Car {
	
	private String engine;
	private String wheel;
	
	protected Car( String engine, String wheel ){
		this.engine = engine;
		this.wheel = wheel;
	}
	
	protected Car(){
		
	}
	

	public String getEngine() {
		return engine;
	}

	public void setEngine(String engine) {
		this.engine = engine;
	}

	public String getWheel() {
		return wheel;
	}

	public void setWheel(String wheel) {
		this.wheel = wheel;
	}

}
2、构建者工具接口

/**
 * 汽车构建工具统一接口
 * 
 * 封装汽车及其子部件构建细节
 * 
 * @author ypqiao
 *
 */
public interface Builder {
	
	/**
	 * 构建引擎
	 * @throws Exception
	 */
	public void buildEngine() throws Exception;
	
	/**
	 * 构建轮子
	 * @throws Exception
	 */
	public void buildWheel() throws Exception;
	
	/**
	 * 构建汽车
	 * @return
	 * @throws Exception
	 */
	public Car getCar() throws Exception;
	

}
2.1、宝马构建工具实现

/**
 * 宝马汽车构建工具
 * 
 * @author ypqiao
 *
 */
public class BaomaBuilder implements Builder {
	
	private String engine;
	private String wheel;

	@Override
	public void buildEngine() throws Exception {
		engine = "BaoMa-engine";
	}

	@Override
	public void buildWheel() throws Exception {
		wheel = "BaoMa-wheel";
	}

	@Override
	public Car getCar() throws Exception {
		return  new Car(engine,wheel);
	}
}
2.2、奔驰构建工具实现

/**
 * 奔驰汽车构建工具
 * 
 * @author ypqiao
 *
 */
public class BenchBuilder implements Builder {
	
	private String engine;
	private String wheel;

	@Override
	public void buildEngine() throws Exception {
		engine = "Bench-engine";
	}

	@Override
	public void buildWheel() throws Exception {
		wheel = "Bench-wheel";
	}

	@Override
	public Car getCar() throws Exception {
		return  new Car(engine,wheel);
	}

	
}
3、构建者类

/**
 * 构建者
 * 
 * 封装构建工具构建细节
 * 
 * @author ypqiao
 *
 */
public class Director {
	
	public Builder builder;
	
	public Director(Builder builder) {
		this.builder = builder;
	}

	public void constrct() throws Exception{
		
		if( builder == null ){
			throw new RuntimeException(" no builder ");
		}
		
		builder.buildEngine();
		builder.buildWheel();
	}
	
	

}

4、消费者(此时它想创建一辆汽车,只需调用构建工具盒构建者即可,不必知道汽车具体的创建细节)

/**
 * 汽车产品消费类
 * 
 * @author ypqiao
 *
 */
public class Customer {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		//Builder baomaBuilder = new BaomaBuilder();
		Builder benchBuilder = new BenchBuilder();
		
		Director director = new Director(benchBuilder);
		director.constrct();
		
		Car car = benchBuilder.getCar();
		
		System.out.println(car.getEngine()+"\n"+car.getWheel());

	}

}







评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值