设计模式学习之生成器模式(Builder)

作用:一个类可以有不同的部件供选择,这些部件变化频繁,但是有稳定的算法来组合它们。
实现要点:关注对象的构建过程,也就是上面说的“算法”,一步一步生成你需要的复杂对象。
UML:

代码:

 class Director
{

public HomeBuilder getBuilder(string homeType)
{
if (homeType == "simple")
{
return new SimpleBuilder();
}
else
{
return new AdvancedBuilder();
}
}
}
public abstract class Product
{
public abstract string getName();
}
class Bed : Product
{
public override string getName()
{
return "Bed";
}
}
class Desk : Product
{
public override string getName()
{
return "Desk";
}

}

//稳定的算法:简易的房子有2张床,高级的房子有3张床和5张桌子
public abstract class HomeBuilder
{
protected Product mybed, mydesk;
public abstract ArrayList buildAHouse();
}
class SimpleBuilder : HomeBuilder
{
public override ArrayList buildAHouse()
{
mybed
= new Bed();
string name1 = mybed.getName();
ArrayList newHouse
= new ArrayList();
newHouse.Add(
"this is a simplehouse:");
for (int i = 0; i < 2; i++)
{
newHouse.Add(name1);
}
return newHouse;

}
}
class AdvancedBuilder : HomeBuilder
{
public override ArrayList buildAHouse()
{
mybed
= new Bed();
string name1 = mybed.getName();
mydesk
= new Desk();
string name2 = mydesk.getName();
ArrayList newHouse
= new ArrayList();
newHouse.Add(
"this is a advancedhouse:");
for (int i = 0; i < 3; i++)
{
newHouse.Add(name1);
}
for (int i = 0; i < 5; i++)
{
newHouse.Add(name2);
}

return newHouse;
}
}
//-----------------------执行---------------------------
class Program
{
static void Main(string[] args)
{
Director director
= new Director();
HomeBuilder builder1
= director.getBuilder("simple");
HomeBuilder builder2
= director.getBuilder("advanced");
ArrayList house1
= builder1.buildAHouse();
ArrayList house2
= builder2.buildAHouse();

for (int i = 0; i < house1.Count; i++)
{
Console.WriteLine(house1[i].ToString());
}
for (int i = 0; i < house2.Count; i++)
{
Console.WriteLine(house2[i].ToString());
}
Console.ReadLine();

}
}

备注:上面代码,两个Builder分别是SimpleBuilder和AdvancedBuilder。directory只是一个简单工厂,他确定使用哪个builder。
生成器模式和抽象工厂模式比较相似,两者都返回有许多方法和对象组成的产品。它们之间的主要差别是:抽象工厂只返回一系列相关的对象,而生成器则是根据提供给他的数据一步一步构建出一个复杂的对象(上例中的newHouse),他更关注对象的构建过程。
posted @ 2008-11-10 17:19  MichaelChen  阅读(313)  评论(0编辑  收藏  举报