建造者(Builder)模式:将一个复杂对象拆解成多个相对简单的部分,根据不同需要分别实现它们,
最后组成该复杂对象。
建造者模式和抽象工厂方法区别在于,前者核心是将一个复杂的对象拆解成一个小的部分然后由所有整体
组成一个复杂的对象提供给调用者。
而后者并没有拆的概念,将各个分部组合起来的不是一个单独存在的对象。
using System;
namespace CSspace
{
public class House {
private string Floor;
private string Door;
private string Wall;
private string Window;
private string Celling;
private House (Builder builder)
this.Floor = builder.Floor;
this.Door = builder.Door;
this.Wall = builder.Wall;
this.Window = builder.Window;
this.Celling = builder.Celling;
}
public override string ToString()
{
return this.Door+"-"+this.Window+"-"+this.Wall+"-"+"-"+this.Floor+"-"+this.Celling;
}
public class Builder
{
public string Door{get;set;}
public string Floor{get;set;}
public string Wall{get;set;}
public string Window{get;set;}
public string Celling{get;set;}
public Builder(string door, string window){
this.Door = door;
this.Window = window;
}
public Builder BuildDoor(string door){ this.Door = door; return this;}
public Builder BuildWall(string wall){this.Wall = wall; return this;}
public Builder BuildWindow(string window){this.Window = window; return this;}
public Builder BuildFloor(string floor){this.Floor = floor; return this;}
public Builder BuildCelling(string celling){this.Celling = celling; return this;}
public House build(){
return new House(this);
}
}
}
public class Test {
public static void Main(){
House house = new House.Builder("防盗门","铝合金窗")
.BuildFloor("大理石地板")
.BuildWall("刷大白")
.BuildCelling("继承吊顶")
.build();
Console.WriteLine(house.ToString());
}
}
}