缘起:某一设施由几个部分组成,这些部分的组成不变(系统的高层抽象保持稳定),但每个部分要富于变化。
动机(motivation):
“一个复杂对象”的创建工作,通常由各个部分的子对象用一定算法构成;这些部分经常面临剧烈的变化,但组合算法却相对稳定。
意图(intent):
将一个复杂对象的构建与其表示相分离,使同样的构建过程可以创建不同的表示。
结构(Structure):
协作(Collaborations)
应用:
abstract class House
{
}
public abstract class Builder
{
public abstract void BuildDoor();
public abstract void BuildWindows();
public abstract House GetHouse(); //house is made of these elements listed above
}
public class GameManager
{
public static House CreateHouse(Builder builder)
{ //这里使基本稳定的,即所谓的算法
builder.BuildDoor();
builder.BuildDoor();
builder.BuildWindows();
return builder.GetHouse();
}
}
public class RomanHouse:House
{
}
public class RomanHouseBuilder: Builder
{
public override void BuildDoor();
public override void BuildWindows();
public override House GetHouse(); //house is made of these elements listed above
}
class App
{
public static void Main()
{ //这样使变动的
House house = GameManager.CreateHouse(new RomainHouseBuilder);
//在。net中可以利用类型反射,这样客户端就不用重新编译,new RomainHouseBuilder就不用变动了
string assemblyName= ConfigurationSettings[“BuilderAssembly”];
string builderName = ConfigurationSettings[“Builder”];
Assembly assembly = Assembly.Load(assemblyName);
Typy t= assembly.GetType(“builderName”);
Builder builder = Active.CreateInstance(t);
House house = GameManager.CreateHouse(builder);
}
}
要点:
1. BuilderPart方法为虚函数,可返回接口或抽象类
2. 难以应对“分步骤构建算法”的需求变动