문제

I'm refactoring a class (Controller) which handles a tree. Because there are many different types (around 20) in the tree. It uses often following structure to handle for example an insertion:

  1. Determine type of the object
  2. Do some type specific things and insert object into tree

    public void AddChildren(Animal animal)
    {
        var cat = animal as Cat;
        if (cat != null)
        {
            AddCat(cat);
            return;
        }
    
        var dog = animal as Dog;
        if (dog != null)
        {
            AddDog(dog);
            return;
        }
    }
    
    public void AddCat(Cat cat)
    {
        //do some cat specific things
        //add to tree
    }
    

So the logic for determining the type of an object is used in many places within the class. Is there a good approach to concentrate this logic in one place?

도움이 되었습니까?

해결책

You might want to use the Strategy(GoF) pattern:

http://en.wikipedia.org/wiki/Strategy_pattern

  1. Create an interface LivingAnimal with a method addToTree(Tree tree)
  2. Implement this interface in objects Cat, Dog, etc.
  3. in Cat.addToTree(Tree tree) (and other objects), do your cat specific stuff, and add itself in the tree (tree.add(this))
  4. In your controller, create a method addChildren(LivingAnimal p). This method finds the correct type of object (Cat, Dog, etc.) and calls addToTree(tree) on it.

When you're using Strategy(GoF), you're delegating the responsibility to the right object. In this case, you'll simplify your controller and keep a high cohesion on the various objects.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top