简体   繁体   English

这种总体设计模式有名称吗?

[英]Is there a name for this aggregative design pattern?

I frequently find myself using the following pattern when I want to avoid using large switch statements (please excuse the hackneyed 'animal' theme): 当我想避免使用较大的switch语句时,经常会使用以下模式(请原谅“动物”主题):

public enum AnimalType { Dog, Cat, Hamster }

public interface IAnimal
{
    AnimalType AnimalType { get; }
}

public class Cat : IAnimal
{
    public AnimalType AnimalType { get { return AnimalType.Cat; } }
}

public class AnimalAggregator
{
    private readonly IDictionary<AnimalType, IAnimal> _animals;

    public AnimalAggregator(IEnumerable<IAnimal> animals)
    {
        _animals = animals.ToDictionary(a => a.AnimalType);
    }

    public IAnimal Get(AnimalType animalType)
    {
        IAnimal animal;
        return _animals.TryGetValue(animalType, out animal) ? animal : null;
    }
}

In the above example I would take a dependency on AnimalAggregator and allow an IoC container to wire up the injection of all IAnimal s. 在上面的示例中,我将依赖于AnimalAggregator并允许IoC容器连接所有IAnimal的注入。 Then instead of writing out a large switch statement for retrieving the IAnimal associated with AnimalType.Cat , I just call animalAggregator.Get(AnimalType.Cat) . 然后,我没有写一个大的switch语句来检索与IAnimal关联的AnimalType.Cat ,而是调用animalAggregator.Get(AnimalType.Cat)

I have used this pattern (and variations thereof) many times in my projects but never known what to call it - I tend to go with "aggregator" but I'm not sure that's accurate. 我在项目中多次使用这种模式(及其变体),但不知道该怎么称呼-我倾向于使用“聚合器”,但是我不确定这是正确的。 I have never seen it outside of my own code though. 不过,我从未在自己的代码之外看到它。

Does it have a name? 它有名字吗?

This feels to me like it should be an abstract factory pattern: 在我看来,这应该是一种抽象的工厂模式:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes. 提供一个用于创建相关或依赖对象族的接口,而无需指定其具体类。

抽象图案图

You will then have an AnimalFactory with different GetMethods for each animal type. 然后,您将拥有一个AnimalFactory,每种动物类型具有不同的GetMethods。 I guess you could have a generic get method but this defeats the purpose of the abstract factory. 我想您可能有一个通用的get方法,但这违反了抽象工厂的目的。 Since you are in any way limited by the enum why not have a method per type. 由于您受到枚举的任何限制,所以为什么每种类型都没有方法。

For more info see http://www.dofactory.com/Patterns/PatternAbstract.aspx 有关更多信息,请参见http://www.dofactory.com/Patterns/PatternAbstract.aspx

I think this is just a variation of the abstract factory pattern. 我认为这只是抽象工厂模式的一种变体。 The only thing left to do is make AnimalAggregator extend an IAnimalFactory interface and change client code to take a dependency on IAnimalFactory instead of AnimalAggregator . 剩下要做的唯一事情就是让AnimalAggregator扩展IAnimalFactory接口并更改客户端代码以依赖IAnimalFactory而不是AnimalAggregator

public inteface IAnimalFactory
{
    IAnimal Get(AnimalType t);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM