其他分享
首页 > 其他分享> > 6.创建型模式(建造者模式)

6.创建型模式(建造者模式)

作者:互联网

1.概述

具体实现:实现家庭装修,包含墙体,电视与沙发。运用建造者模式完成装修实现


1.产品角色Product

public class WallProduct {
	private String wall;
	private String TV;
	private String sofa;

	public void setWall(String wall) {
		this.wall = wall;
	}

	public void setTV(String TV) {
		this.TV = TV;
	}

	public void setSofa(String sofa) {
		this.sofa = sofa;
	}

	//相当于show方法,展现墙体装修效果
	@Override
	public String toString() {
		return "WallProduct{" +
				"wall='" + wall + '\'' +
				", TV='" + TV + '\'' +
				", sofa='" + sofa + '\'' +
				'}';
	}
}

2.抽象建造者Builder

public abstract class AbstractWallBuilder {
	protected WallProduct product = new WallProduct();

	public abstract void buildWall();

	public abstract void buildTV();

	public abstract void buildSofa();

	public WallProduct getProduct(){
		return product;
	}
}

3.具体建造者1-ConcreteWallBuilder

public class ConcreteWallBuilder1 extends AbstractWallBuilder{
	@Override
	public void buildWall() {
		product.setWall("wall1");
	}

	@Override
	public void buildTV() {
		product.setTV("TV1");
	}

	@Override
	public void buildSofa() {
		product.setSofa("Sofa1");
	}
}

4.指挥者Director

public class WallDirector {
	private AbstractWallBuilder builder;

	public WallDirector(AbstractWallBuilder builder) {
		this.builder = builder;
	}

	//调用具体工人进行装修
	public WallProduct decorate() {
		builder.buildSofa();
		builder.buildTV();
		builder.buildWall();
		return builder.getProduct();
	}

}

标签:builder,String,创建,void,建造,模式,sofa,public
来源: https://www.cnblogs.com/jingqz/p/15401508.html