用于解释要使用的对象类型的设计模式

时间:2014-10-26 09:34:17

标签: design-patterns

我有一种情况需要找出应该处理给定规范并重用对象的对象类型。这是一个例子:

interface ICar {
    int getMaxSpeed();
}

class Mercedes implements ICar {}
class Ferrari implements ICar {}
class Jauguar implements ICar {}

使用:

for(Spec spec : specs) { //spec will contain only a blob.. not a actual car type; I need to interpret it somehow
     //do something here to match spec with type of car..
     ICar car = getSpecificCarSomehowWithoutSwitchCase(spec);
}

我想到了两种可行的方法:

  1. 使用Builder \ Abstract Factory模式解释和创建汽车(或返回已创建的现有对象)

  2. 添加" IsMe" ICar的方法,汇集了Car对象的实例,并使用spec作为参数调用它们,如果是这种情况则返回true。

  3. 我喜欢方法#2,特别是因为我可以并且想要重用已经创建的对象。我查看了对象池设计模式但是" checkout"方法没有采用密钥\ crietrion来查找对象。

    我是否错过了一些模式\方法?

    提前致谢, -Neel。

3 个答案:

答案 0 :(得分:0)

我认为你需要使用抽象工厂,似乎你已经知道了模式,如果不是: http://en.wikipedia.org/wiki/Abstract_factory_pattern C#的另一个好网站是: http://www.dofactory.com/

如果这还不够,明天我会写一些伪代码:)

答案 1 :(得分:0)

我最近做过这样的事情:

foreach (var factory in availableFactories)
{
   if (factory.IsSuitableFor(thisAbstractItem)
   {
      factory.CreateBasedOn(thisAbstractItem);
   };
};

来电者询问工厂是否可以处理该物品。因此工厂实现如下:

public bool IsSuitableFor(AbstractBase thisAbstractItem)
{
    return thisAbstractItem is anItemICanWorkWith;
}

它适用于我需要的东西,而且非常简单。我想知道你是否可以考虑询问具体的课程,如果他们处理具体案例并根据你的需要改变它?

答案 2 :(得分:0)

看起来你需要一种行为模式。我会考虑命令链(或命令)模式来确定逻辑的处理,然后调用一个汽车类的原型(可重复使用)实例