在软件系统中,有时候面临着“一个复杂对象”的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的算法确相对稳定。如何应对这种变化?如何提供一种“封装机制”来隔离出“复杂对象的各个部分”的变化,从而保持系统中的“稳定构建算法”不随着需求改变而改变?这就是要说的建造者模式。
using System;
namespace MyApp
{
class Program
{
static void Main()
{
Animal person = new Person();
CreateAnimal createAnimal = new CreateAnimal(person);
createAnimal.Create();
Console.WriteLine();
Animal monkey = new Monkey();
createAnimal = new CreateAnimal(monkey);
createAnimal.Create();
Console.ReadKey();
}
}
abstract class Animal
{
public abstract void AddBody();
public abstract void AddHand();
public abstract void AddLeg();
public abstract void AddHead();
}
class Person : Animal
{
public override void AddBody()
{
Console.WriteLine("Person's body was created...");
}
public override void AddHand()
{
Console.WriteLine("Person's hands were created...");
}
public override void AddLeg()
{
Console.WriteLine("Person's legs were created...");
}
public override void AddHead()
{
Console.WriteLine("Person's head was created...");
}
}
class Monkey : Animal
{
public override void AddBody()
{
Console.WriteLine("Monkey's body was created...");
}
public override void AddHand()
{
Console.WriteLine("Monkey's hands were created...");
}
public override void AddLeg()
{
Console.WriteLine("Monkey's legs were created...");
}
public override void AddHead()
{
Console.WriteLine("Monkey's head was created...");
}
}
class CreateAnimal
{
Animal animal;
public CreateAnimal(Animal theAnimalInstance)
{
animal = theAnimalInstance;
}
public void Create()
{
animal.AddBody();
animal.AddHand();
animal.AddLeg();
animal.AddHead();
}
}
}
1090

被折叠的 条评论
为什么被折叠?



