0
点赞
收藏
分享

微信扫一扫

设计模式(1) -- 创建模式

创建模式

  1. 一种封装创建对象的模式它包括:
  2. 抽象工厂模式(Abstract Factory)
  3. 构造者模式(Builder)
  4. 工厂方法(Factory Method)
  5. 原型对象(Prototype)
  6. 单例模式(Singleton)

Abstract Factory

提供一个接口,用于创建一组相关或依赖的对象而无需指定它们的具体类型。

从关键字"一组相关或依赖的对象"可知:

  • 工厂要创建多个对象
  • 创建的对象们是相互关联或相互依赖的

实例--动物世界

模拟食物链

class AnimalWorld
{
  private Herbivore _herbivore;
  private Carnivore _carnivore;
  // Constructor
  public AnimalWorld(AnimalFactory factory)
   {
       _carnivore = factory.CreateCarnivore();
       _herbivore = factory.CreateHerbivore();
   }
    public void RunFoodChain()
    {
        _carnivore.Eat(_herbivore);
    }
}

  • AnimalWorld就是我们的客户端,客户端的代码不能被轻易改变。
  • AnimalWorld中Carnivore(食肉动物)吃Herbivore(食草动物)
  • 构造AnimalWorld需要提供AnimalFactory对象
  • AnimalFactory负责创建_herbivore和_carnivore

AnimalFactory就是抽象工厂类,它负责创建一组对象(_herbivore和_carnivore),并且_herbivore和_carnivore具有一定的依赖性(_carnivore.Eat(_herbivore)).

食肉动物吃食草动物 (抽象)

abstract class Herbivore
{
}

abstract class Carnivore
{
    public abstract void Eat(Herbivore h);
}

abstract class AnimalFactory
{
    public abstract Herbivore CreateHerbivore();
    public abstract Carnivore CreateCarnivore();
}

狮子吃角马(实现)

class Wildebeest: Herbivore
{
}

class Lion: Carnivore
{
    public void Eat(Herbivore h)
    {
        Console.WriteLine(this.GetType().Name +
              " eats " + h.GetType().Name);
    }
}

class WildebeestLionFactory: AnimalFactory
{
    public Herbivore CreateHerbivore()
    {
        return new Wildebeest();
    }
    public Carnivore CreateCarnivore()
    {
        return new Lion();
    }
}

狼吃野牛(实现)

class Bison: Herbivore
{
}

class Wolf : Carnivore
{
    public void Eat(Herbivore h)
    {
        Console.WriteLine(this.GetType().Name +
              " eats " + h.GetType().Name);
    }
}

class BisonWolfFactory: AnimalFactory
{
    public Herbivore CreateHerbivore()
    {
        return new Bison();
    }
    public Carnivore CreateCarnivore()
    {
        return new Wolf();
    }
}

测试程序

class MainApp
{
    public static void Main()
    {
        // Create and run the WildebeestLionFactory animal world
        ContinentFactory africa = new WildebeestLionFactory();
        AnimalWorld world = new AnimalWorld(africa);
        world.RunFoodChain();
        
         // Create and run the BisonWolfFactory animal world
        ContinentFactory america = new BisonWolfFactory();
        world = new AnimalWorld(america);
        world.RunFoodChain();
        
        Console.ReadKey();
     }
}

用WildebeestLionFactory和BisonWolfFactory创建了两个AnimalWorld,在上面的代码中我们甚至都不需要知道Wildebeest,Lion , Bison 和 Wolf的实现。

未完待续...


举报

相关推荐

0 条评论