今天重讀建造者模式【Build Pattern】,終於明白了其存在之意圖和應用之情境。
其意在建立一個複雜的對象,這個對象由一系列穩定的動作組成,單不同的產品具體的動作實現又不一樣。而其中重點在於將一個複雜的構建與其表示相分離,使得同樣的構建過程可以建立不同的表示
這個抽象和封裝的過程非常類似於模板方法模式,但是要注意他們的關注點不同:模板方法重在“行為”,是指穩定的一系列動作的實現,屬於行為型模式;而建造者模式則意在對象的建立,建立一個複雜的、具有多個實現步驟的對象,屬於建立型模式。
下面的代碼實現電腦的組裝。一台電腦可看做一個複雜的對象,其組裝過程需要安裝cpu,主板,記憶體,硬碟等組件。當然不同品牌的電腦安裝的組件又不相同,但是這個過程中每個步驟都是不可少的,是穩定的。
結構圖:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BuildPattern
{
class Program
{
static void Main(string[] args)
{
Computer pc = new MsComputer();
Build build = new Build(pc);
build.BeginBuildComputer();
pc.ShowMyComputer();
}
}
//產品抽象類別
abstract class Computer
{
public string Cpu { set; get; }
public string HardDisk { set; get; }
public string KeyBoard { set; get; }
public string Memory { set; get; }
public abstract void SetCpu();
public abstract void SetHardDisk();
public abstract void SetKeyBoard();
public abstract void SetMemory();
public void ShowMyComputer()
{
Console.WriteLine("------------");
Console.WriteLine("My Compter Config:");
Console.WriteLine("Cpu:" + Cpu);
Console.WriteLine("KeyBoard:" + KeyBoard);
Console.WriteLine("HardDisk:" + HardDisk);
Console.WriteLine("Memory:" + Memory);
}
}
//具體類
class InterComputer : Computer
{
public override void SetCpu()
{
Console.WriteLine("setting Inter Cpu for this computer");
Cpu = "Inter Cpu";
}
public override void SetHardDisk()
{
Console.WriteLine("setting Inter HardDisk for this computer");
HardDisk = "Inter HardDisk";
}
public override void SetKeyBoard()
{
Console.WriteLine("setting Inter KeyBoard for this computer");
KeyBoard = "Inter KeyBoard";
}
public override void SetMemory()
{
Console.WriteLine("setting Inter Memory for this computer");
Memory = "Inter Memory";
}
}
//具體類
class MsComputer : Computer
{
public override void SetCpu()
{
Console.WriteLine("setting Ms Cpu for this computer");
Cpu = "Ms Cpu";
}
public override void SetHardDisk()
{
Console.WriteLine("setting Ms HardDisk for this computer");
HardDisk = "Ms HardDisk";
}
public override void SetKeyBoard()
{
Console.WriteLine("setting Ms KeyBoard for this computer");
KeyBoard = "Ms KeyBoard";
}
public override void SetMemory()
{
Console.WriteLine("setting Ms Memory for this computer");
Memory = "Ms Memory";
}
}
//建造者
class Build
{
Computer computer;
public Build(Computer computer)
{
this.computer = computer;
}
public void BeginBuildComputer()
{
computer.SetCpu();
computer.SetHardDisk();
computer.SetKeyBoard();
computer.SetMemory();
}
}
}
學習參考:
http://www.cnblogs.com/Terrylee/archive/2005/12/19/299878.html
http://www.cnblogs.com/zhenyulu/articles/37378.aspx
大話設計模式之建造者模式