建造者模式
将复杂的对象的实现过程与表现形式进行分离。
此模式用于创建一些复杂的对象,内部建造顺序稳定,但是建造的内容有复杂的变化。此模式将建造代码与表示代码分离,建造者隐藏了产品的组装过程,通过不同的建造者定义不同的产品内部表示。
Builder.PNG
代码语言:javascript复制class Program
{
static void Main(string[] args)
{
Director director = new Director();
Builder builder = new DellWorker();
director.CreateComputer(builder);
Computer computer = builder.GetComputer();
computer.Show();
}
}
class Computer
{
List<string> computerCom =new List<string>();
public void Add(string com)
{
computerCom.Add(com);
}
public void Show()
{
foreach(var item in computerCom)
{
Console.WriteLine("Build : " item);
}
}
}
abstract class Builder
{
protected Computer computer = new Computer();
public abstract void AddCPU();
public abstract void AddGPU();
public abstract void AddRAM();
public abstract Computer GetComputer();
}
class DellWorker : Builder
{
public override void AddCPU()
{
computer.Add("INTELCPU");
}
public override void AddGPU()
{
computer.Add("NAVIDGPU");
}
public override void AddRAM()
{
computer.Add("CRAM");
}
public override Computer GetComputer()
{
return computer;
}
}
class Director
{
public void CreateComputer(Builder builder)
{
builder.AddCPU();
builder.AddGPU();
builder.AddRAM();
}
}