四.案例分析(Example)
1、场景
假设房子只有房顶和墙(Roof And Walls)
Jane和 Joe两个客户需要从建造商Bob那里买房子。Jane需要1个房顶(Roof)和4面墙(Walls)的房子,Joe需要1个房顶(Roof)和7面墙(Walls)的房子。建造商需要通过建造者模式实现客户的个性要求。
此时建造商Bob(Contractor)就是指挥者(Director),TownHomeSubContractor和SingleFamilySubContractor就是建造者类(Builder Class),房子就是产品(House is Product).如下图所示
House类:House is Pruduct
Contractor类,指挥者
MakeHouse()方法,指挥房子建造过程。
ISubConstractor接口,建造者接口,
AddRoof().添加房顶方法
AddWalls(),添加墙的方法
GetHouse(),获得构建好的房子方法。
TownHomeSubContractor类,具体的建造者,实现建造者接口方法。
建造一个房顶和四面墙,以满足Jane 的要求。
SingleFamilySubContractor类,具体的建造者,实现建造者接口方法。
建造一个房顶和七面墙,以满足Joe的要求。
2、代码
1、产品House
|
public class House
{
public string Roof { get; set; }
public string Walls { get; set; }
}
|
2、指挥者类Contractor
|
public class Contractor
{
public void MakeHouse(ISubContractor contractor)
{
contractor.AddRoof();
contractor.AddWalls();
}
}
|
3、抽象建造者ISubContractor及其具体建造者TownHomeSubContractor,SingleFamilySubContractor
|
//Sub Contractor interface (IBuilder)
public interface ISubContractor
{
void AddRoof();
void AddWalls();
House GetHouse();
}
//Concrete Builder Classes
public class TownHomeSubContractor : ISubContractor
{
private House _house = new House();
public void AddRoof()
{
_house.Roof = "Adding a small roof";
}
public void AddWalls()
{
_house.Walls = "Adding 4 Walls";
}
public House GetHouse()
{
return _house;
}
}
public class SingleFamilySubContractor : ISubContractor
{
private House _house = new House();
public void AddRoof()
{
_house.Roof = "Adding a large roof";
}
public void AddWalls()
{
_house.Walls = "Adding 7 Walls";
}
public House GetHouse()
{
return _house;
}
}
|
4、客户端代码
|
static void Main(string[] args)
{
//Jane wants a Town Home
Console.WriteLine("Building a Town Home for Jane..");
Contractor contractor = new Contractor();
ISubContractor subContractorTownHome = new TownHomeSubContractor();
contractor.MakeHouse(subContractorTownHome);
House townHome = subContractorTownHome.GetHouse();
Console.WriteLine(townHome.Roof + "..");
Console.WriteLine(townHome.Walls + "..");
//Joe wants a Single Family Home
Console.WriteLine("\nBuilding a Town Home for Joe..");
ISubContractor subContractorSingleFamily = newSingleFamilySubContractor();
contractor.MakeHouse(subContractorSingleFamily);
House singleFamilyHouse = subContractorSingleFamily.GetHouse();
Console.WriteLine(singleFamilyHouse.Roof + "..");
Console.WriteLine(singleFamilyHouse.Walls + "..");
}
|
3、程序运行结果
五、总结(Summary)
建造者模式(Builder Pattern),将一个复杂对象的构建与它的表示分离,使的同样的构建过程可以创建不同的表示。建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时适用的模式。
本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/262825,如需转载请自行联系原作者