建造者模式
将复杂的对象的实现过程与表现形式进行分离。
此模式用于创建一些复杂的对象,内部建造顺序稳定,但是建造的内容有复杂的变化。此模式将建造代码与表示代码分离,建造者隐藏了产品的组装过程,通过不同的建造者定义不同的产品内部表示。
Builder.PNGclass 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();
}
}
Lua实现:
-- [[将复杂的对象的实现过程与表现形式进行分离。]]
Product = {}
function Product:new(o)
o = o or {};
setmetatable(o,self);
self.__index = self;
return o;
end
function Product:Show()
print(self.unit);
end
Builder = {}
function Builder:new(o)
o = o or {};
setmetatable(o,self);
self.__index = self;
return o;
end
ComputerBuilder = Builder:new();
function ComputerBuilder:new(o)
o = o or {}
setmetatable(o,self)
o.product = Product:new();
self.__index = self;
return o;
end
function ComputerBuilder : AddCpu()
if self.product.unit == nil then
self.product.unit = "Computer :";
end
self.product.unit = self.product.unit .. "英特尔CPU9900k; ";
end
function ComputerBuilder : AddGpu()
self.product.unit = self.product.unit .. "GPU2080TI; ";
end
function ComputerBuilder : AddRAM()
self.product.unit = self.product.unit .. "RAM64G; ";
end
Director = {}
function Director:new(o)
o = o or {};
setmetatable(o,self);
self.__index = self;
return o;
end
function Director:Construct(builder)
if builder ~= nil then
builder:AddCpu();
builder:AddGpu();
builder:AddRAM();
builder.product:Show();
end
end
combuilder = ComputerBuilder : new();
comDirector = Director:new();
comDirector = Director:Construct(combuilder);
网友评论