java设计模式学习笔记-构建模式

本文深入解析构建者模式在汽车产品设计与实现中的应用,详细阐述了产品、构建者工具接口、构建者接口实现类及构建类的角色与作用。同时,讨论了该模式的优点和缺点,强调其在产品差别不大的场景下,能够有效控制产品内部表象的变化,并简化产品的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该模式有4个角色:构建工具接口、构建接口实现类、构建类、产品类

1、产品

package model06.create;

public class Car{
	private String engine;
	private String wheel;
	
	protected Car(String enqine, 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 this.wheel;
	}
	
	public void setWheel(String wheel){
		this.wheel = wheel;
	}
}

2、构建者工具接口

package model06.create;

public interface Builder{
	public void buildEngine() throws Exception;
	public void buildWheel() throws Exception;
	public Car getCar() throws Exception;
}

3、构建者工具接口的实现

package model06.create;

public class CarBuilder inplements Builder{
	private String engine;
	private String wheel;
	public void buildEngine() throws Exception{
		this.engine = "engine";
	}
	
	public void buildWheel() throws Exceptino{
		this.wheel = "wheel";
	}
	
	public Car getCar() throws Exception{
		return new Car(engine, wheel);
	}
}

4、构建者类

package model06.create;

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();
	}
}

构造者模式的优缺点

优点

1:建造模式的使用使得产品的内部表象可以独立地变化。使用建造模式可以使客户端不必知道产品内部组成的细节
2:每一个Builder都相对独立,而与其他的Builder无关
3:模式所建造的最终产品更易于控制

缺点

创建者模式比较符合产品差别不大的对象的创建,如果差别很大,就会导致非常多的具体的创建者,这时候最好结合工厂方法模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值