设计模式(1)抽象工厂模式

模式介绍

抽象工厂模式是一种创建模式,它定义接口来创建相关对象族,而不指定它们的实际实现。
使用此模式时,你将创建返回许多相关对象的工厂。这种模式实现了更大的体系结构,如依赖注入。

示例

比如有Sandwich(三明治) 和 Dessert(甜点)
adults(成人)和 kids(小孩)喜欢吃的都不一样

抽象的Sandwich 和 Dessert

/// <summary>
/// An abstract object.
/// </summary>
abstract class Sandwich { }

/// <summary>
/// An abstract object.
/// </summary>
abstract class Dessert { }

具体的Sandwich 和 具体的Dessert

/// <summary>
/// A ConcreteProduct
/// </summary>
class BLT : Sandwich { }

/// <summary>
/// A concrete object
/// </summary>
class GrilledCheese : Sandwich { }

/// <summary>
/// A ConcreteProduct
/// </summary>
class CremeBrulee : Dessert { }

/// <summary>
/// A concrete object
/// </summary>
class IceCreamSundae : Dessert { }

抽象工厂:声明抽象方法,用于创建Sandwich 和 Dessert

/// <summary>
/// The AbstractFactory class, which defines methods for creating abstract objects.
/// </summary>
abstract class RecipeFactory
{
    public abstract Sandwich CreateSandwich();
    public abstract Dessert CreateDessert();
}

成人烹饪工厂:继承抽象工厂

/// <summary>
/// A ConcreteFactory which creates concrete objects by implementing the abstract factory's methods.
/// </summary>
class AdultCuisineFactory : RecipeFactory
{
    public override Sandwich CreateSandwich()
    {
        return new BLT();
    }

    public override Dessert CreateDessert()
    {
        return new CremeBrulee();
    }
}

小孩烹饪工厂:继承抽象工厂

/// <summary>
/// A concrete factory which creates concrete objects by implementing the abstract factory's methods.
/// </summary>
class KidCuisineFactory : RecipeFactory
{
    public override Sandwich CreateSandwich()
    {
        return new GrilledCheese();
    }

    public override Dessert CreateDessert()
    {
        return new IceCreamSundae();
    }
}

客户端调用:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Who are you? (A)dult or (C)hild?");
        char input = Console.ReadKey().KeyChar;
        RecipeFactory factory;
        switch(input)
        {
            case 'A':
                factory = new AdultCuisineFactory();
                break;

            case 'C':
                factory = new KidCuisineFactory();
                break;

            default:
                throw new NotImplementedException();

        }

        var sandwich = factory.CreateSandwich();
        var dessert = factory.CreateDessert();

        Console.WriteLine("\nSandwich: " + sandwich.GetType().Name);
        Console.WriteLine("Dessert: " + dessert.GetType().Name);

        Console.ReadKey();
    }
}

源代码

https://github.com/exceptionnotfound/DesignPatterns/tree/master/AbstractFactory

原文

https://www.exceptionnotfound.net/the-daily-design-pattern-abstract-factory/

posted @ 2018-10-16 13:54  talentzemin  阅读(167)  评论(0编辑  收藏  举报