四.案例分析(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
{
//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,如需转载请自行联系原作者