一、介绍
生成器模式有点像是抽象工厂模式,两者都返回由一些方法和对象组成的类,主要的区别在于,抽象工厂返回系列相关类,生成器则根据向其提交的数据来逐步构造出复杂的对象。
二、UML图
三、示例
//动物
View Code
using System.Collections.Generic; using System.Linq; using System.Text; namespace Builder { /// <summary> /// 抽象类 /// </summary> public abstract class AbstractAnimal { public abstract string GetName(); } /// <summary> /// 狗类 /// </summary> public class Dog : AbstractAnimal { public override string GetName() { return "Dog"; } } /// <summary> /// 猫 /// </summary> public class Cat : AbstractAnimal { public override string GetName() { return "Cat"; } } }
//行为
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Builder { public interface IAction { string Eat(); string sound(); } /// <summary> /// 狗行为 /// </summary> public class DogAction : IAction { private AbstractAnimal _animal; public DogAction(AbstractAnimal A) { _animal = A; } #region IAction 成员 public string Eat() { return _animal.GetName()+"啃骨头"; } public string sound() { return _animal.GetName()+"汪汪叫"; } #endregion } /// <summary> /// 猫行为 /// </summary> public class CatAction : IAction { private AbstractAnimal _animal; public CatAction(AbstractAnimal A) { _animal = A; } #region IAction 成员 public string Eat() { return _animal.GetName()+"吃鱼"; } public string sound() { return _animal.GetName()+"喵喵叫"; } #endregion } }
//生成器
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Builder { /// <summary> /// 抽象Builder /// </summary> public abstract class AbstractActionBuilder { public abstract IAction GetBuilder(AbstractAnimal A); } /// <summary> /// 狗Builder /// </summary> public class DogActionBuilder : AbstractActionBuilder { public override IAction GetBuilder(AbstractAnimal A) { return new DogAction(A); } } /// <summary> /// 猫Builder /// </summary> public class CatActionBuilder : AbstractActionBuilder { public override IAction GetBuilder(AbstractAnimal A) { return new CatAction(A); } } }
//Program
View Code
class Program { static void Main(string[] args) { AbstractActionBuilder builder = new DogActionBuilder(); IAction action = builder.GetBuilder(new Dog()); Console.WriteLine(action.Eat()); Console.WriteLine(action.sound()); Console.WriteLine("---------------"); builder=new CatActionBuilder(); action=builder.GetBuilder(new Cat()); Console.WriteLine(action.Eat()); Console.WriteLine(action.sound()); Console.Read(); } }
//运行结果