2

I have 3 classes: **Parent**, **Child1**, and **Child2**. Both Child1 & Child 2 extend Parent and they **cannot** be modified.

There is a class Action defined as follows:

public class Action {
    public static void perform(Parent p) {
        if (p instanceof Child1) {
            action((Child1)p);
        }
        else if (p instanceof Child2) {
            action((Child2)p);
        }
        else {
            action(p);
        }
    }

    private static void action(Parent p) {
        ...
    }
    private static void action(Child1 c1) {
        ...
    }
    private static void action(Child2 c2) {
        ...
    }
}


Parent p = new Child1();
Action.perform(p);

Without instanceof operator, is there any way to get the same behavior as above ?

======
(modified)

PS: the given argument type of Action.perform is Parent, but its value is Child1, so I think method overloading doesn't work ....

Community
  • 1
  • 1
mingyc
  • 526
  • 5
  • 13
  • possible duplicate of [Alternative to instanceof approach in this case](http://stackoverflow.com/questions/5064802/alternative-to-instanceof-approach-in-this-case) – CoolBeans Sep 26 '11 at 14:49
  • 1
    But If those `Parent`, `Child1`, `Child2` classes cannot be modified, how can I implement the visitor pattern ? – mingyc Sep 26 '11 at 15:03

2 Answers2

0

Unfortunately, I think you would have to resort to reflection to solve this.

Daniel Brockman
  • 18,826
  • 3
  • 29
  • 40
0

Here are two C# solutions, one basically is the same but more neat and is good when you have small number of child classes.

public class Parent
{
}

public class Child1 : Parent
{
}

public class Child2 : Parent
{
}

public class Action
{
    private static Dictionary<Type, Action<Parent>> _d = new Dictionary<Type, Action<Parent>>()
                                                    {
                                                        {typeof(Child1), p=>action((Child1)p)},
                                                        {typeof(Child2), p=>action((Child2)p)},
                                                        {typeof(Parent), p=>action(p)}
                                                    };
    public static void perform(Parent p)
    {
        _d[p.GetType()](p);
    }

    private static void action(Parent p)
    {

    }

    private static void action(Child1 c1)
    {

    }
    private static void action(Child2 c2)
    {

    }
}



class Program
{
    static void Main(string[] args)
    {
        Parent p = new Child1();
        Action.perform(p);
    }
}`enter code here`

Anyhow it breaks OCP but is faster than using reflection. This one does not break OCP but uses reflection to fill the dictionary:

public class Action
        {
            private static Dictionary<Type, Action<Parent>> _d;

            static Action()
            {
                Initialize();
            }

            private static void Initialize()
            {
                var methods = typeof(Action)
                    .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                    .Where(IsActionMethod)
                    .ToList();

                _d = methods.ToDictionary(m => m.GetParameters().First().ParameterType,
                                          m => (Action<Parent>) (x => m.Invoke(null, new[] {x})));
            }

            private static bool IsActionMethod(MethodInfo methodInfo)
            {
                var parameters = methodInfo.GetParameters();

                return parameters.Length == 1
                       && typeof(Parent).IsAssignableFrom(parameters.First().ParameterType)
                       && methodInfo.ReturnType == typeof(void);
            }

            public static void perform(Parent p)
            {
                _d[p.GetType()](p);
            }

            private static void action(Parent p)
            {

            }

            private static void action(Child1 c1)
            {

            }

            private static void action(Child2 c2)
            {

            }
}
Yurii Hohan
  • 4,021
  • 4
  • 40
  • 54