Abhijeet
Abhijeet

Reputation: 13856

Obtain different return type objects from factory

I have written following code to include both N1 and N2 wcf service reference. I am attempting to write some kind of factory method to get the particular instance of the proxy object, decided at runtime.

I am not able to use proxyType out varaible assigned by factory in business code, As highlighted below. Can you please suggest what piece of info am I missing ?

How this can be achieved using generics, If my current approach is not correct? Or is there any established design pattern for this scenario ?

namespace N1
{
    public class Proxy1
    {
        public void foo()
        {
            //do something 
        }
    }
}

namespace N2
{
    public class Proxy2
    {
        public void foo()
        {
            //do something 
        }
    }
}

namespace N3
{
    static class Helper
    {
        public static object getProxyInstance(int i, out Type t)
        {
            object objectToReturn = null;
            t = null;
            if (i == 1)
            {
                objectToReturn = new N1.Proxy1();
                t = typeof(N1.Proxy1);
            }
            else if (i == 2)
            {
                objectToReturn = new N2.Proxy2();
                t = typeof(N2.Proxy2);
            }
            return objectToReturn;
        }
    }
}

namespace N4
{
    class BusinessClass
    {
        public void bar()
        {
            Type proxyType;
            var proxyObj = (proxyType)N3.Helper.getProxyInstance(1, out proxyType);
        }
    }
}

var proxyObj = (**proxyType**)N3.Helper.getProxyInstance(1, out proxyType);

Type or namespace proxyType could not be found.

EDIT : Challenge here is - Proxy1 & Proxy2 are classes generated by add service reference command of Visual Studio. If I update service reference, my code changes will vanish, and every time I will have to re-write the code. Thus attempting to write code without wrapping these Proxy classes, manually.

Upvotes: 0

Views: 369

Answers (1)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

public interface IProxy
{
    void Foo();
}

public class Proxy1 : IProxy
{
    public void Foo()
    {
    }
}

public class Proxy2 : IProxy
{
    public void Foo()
    {
    }
}

static class Helper
{
    public static IProxy GetProxyInstance(int i)
    {
        if (i == 1)
        {
            return new Proxy1();
        }
        else if (i == 2)
        {
            return new Proxy1();
        }
        else
        {
            return null;
        }
    }
}

class BusinessClass
{
    public void bar()
    {
        IProxy proxyObj = Helper.GetProxyInstance(1);
        proxyObj.Foo();
    }
}

Upvotes: 2

Related Questions