开发者

Locating dependencies (strategies, repositories etc) depending on subclass type

Imagine I have the following inheritance structure:

AnimalsNamespace.Animal
CatsNamespace.Cat : Animal
DogsNamespace.Dog : Animal

In my application classes, I find myself faced with the following type of code a lot:

void Feed(Animal animal)
{
    if (animal is Cat)
    {
         KernelContainer.Get<ICatFeedingStrategy>().Feed((Cat)animal);
    }
    else if (animal is Dog)
    {
         KernelContainer.Get<IDogFeedingStrategy>().Feed((Dog)animal);
    }
}

This is fine for a while but after I have heaps of these if statements lying around. I then also start getting problems with NHibernate proxies behaving strangely when you request their type etc and things get in a mess.

I could build a Factory class, but I end up with a whole heap of complexity, as just to feed the cat 开发者_开发技巧I have to have: ICatFeedingStrategy, ConcreteCatFeedingStrategy, IAnimalFeedingStrategyFactory, ConcreteAnimalFeedingStrategyFactory... (plus often an abstract base class like AnimalFeedingStrategyBase).

Is there a pattern that can help manage these inheritance structures more efficiently?


Right now you are programming against concrete classes where you should really be programming against interfaces.

The example above might be addressed by using an Abstract Factory to resolve dependencies based on run-time information. Now the Feed method might look like this:

void Feed(Animal animal)
{
    var strategy = this.factory.GetFeedingStrategy(animal);
    strategy.Feed(animal);
}

Where the factory is an injected IFeedingStrategyFactory.

Another option, when you have a finite list of known subtypes, is to use the Visitor pattern.


Maybe a chain of responsibility may help here. First, every "feeder" registers itself in the chain. Then, feed() calls the first "feeder" from the chain. Every feeder knows how to feed its own subclass. Still you have many if-s, but they are closely coupled with their related sub-classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜