设计模式(4)原型模式

模式介绍

原型模式是一种创建型的设计模式,其中使用对象的原型实例创建对象。这种模式对于创建大量对象的实例特别有用,它们都共享一些或全部的值。

示例

没错,我们还是拿三明治举例子...
三明治有很多种,不管两片面包中间夹的啥,它都是三明治。
我们使用原型模式来创建N多三明治吧

首先,整个三明治的原型抽象类

/// <summary>
/// The Prototype abstract class
/// </summary>
abstract class SandwichPrototype
{
    public abstract SandwichPrototype Clone();
}

三明治类,继承原型类

class Sandwich : SandwichPrototype
{
    private string Bread;
    private string Meat;
    private string Cheese;
    private string Veggies;

    public Sandwich(string bread, string meat, string cheese, string veggies)
    {
        Bread = bread;
        Meat = meat;
        Cheese = cheese;
        Veggies = veggies;
    }

    public override SandwichPrototype Clone()
    {
        string ingredientList = GetIngredientList();
        Console.WriteLine("Cloning sandwich with ingredients: {0}", ingredientList.Remove(ingredientList.LastIndexOf(",")));

        return MemberwiseClone() as SandwichPrototype;
    }

    private string GetIngredientList()
    {
        ...
    }
}

class SandwichMenu
{
    private Dictionary<string, SandwichPrototype> _sandwiches = new Dictionary<string, SandwichPrototype>();

    public SandwichPrototype this[string name]
    {
        get { return _sandwiches[name]; }
        set { _sandwiches.Add(name, value); }
    }
}

客户端调用

class Program
{
    static void Main(string[] args)
    {
        SandwichMenu sandwichMenu = new SandwichMenu();

        // Initialize with default sandwiches
        sandwichMenu["BLT"] = new Sandwich("Wheat", "Bacon", "", "Lettuce, Tomato");
        sandwichMenu["PB&J"] = new Sandwich("White", "", "", "Peanut Butter, Jelly");
        sandwichMenu["Turkey"] = new Sandwich("Rye", "Turkey", "Swiss", "Lettuce, Onion, Tomato");

        // Deli manager adds custom sandwiches
        sandwichMenu["LoadedBLT"] = new Sandwich("Wheat", "Turkey, Bacon", "American", "Lettuce, Tomato, Onion, Olives");
        sandwichMenu["ThreeMeatCombo"] = new Sandwich("Rye", "Turkey, Ham, Salami", "Provolone", "Lettuce, Onion");
        sandwichMenu["Vegetarian"] = new Sandwich("Wheat", "", "", "Lettuce, Onion, Tomato, Olives, Spinach");

        // Now we can clone these sandwiches
        Sandwich sandwich1 = sandwichMenu["BLT"].Clone() as Sandwich;
        Sandwich sandwich2 = sandwichMenu["ThreeMeatCombo"].Clone() as Sandwich;
        Sandwich sandwich3 = sandwichMenu["Vegetarian"].Clone() as Sandwich;

        // Wait for user
        Console.ReadKey();
    }
}

总结

原型模式通过从对象的原型实例中克隆对象来初始化对象。当需要创建许多相关项的实例时,它特别有用,每个实例可能与其他实例稍有不同(但不是很不同)。这种模式的主要好处是降低了初始化成本;通过从原型实例中克隆许多实例,理论上可以提高性能。

源代码

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

原文

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

posted @ 2018-10-19 15:57  talentzemin  阅读(129)  评论(0编辑  收藏  举报