从工厂获取不同的返回类型对象

时间:2012-09-17 13:40:14

标签: c# asp.net design-patterns

我编写了以下代码以包含N1和N2 wcf服务引用。我正在尝试编写某种工厂方法来获取代理对象的特定实例,在运行时决定。

我无法在业务代码中使用工厂分配的proxyType out变量,如下所示。你能否建议我错过哪些信息?

如何使用泛型来实现这一点,如果我目前的方法不正确?或者这种情况是否有既定的设计模式?

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.

编辑:这里的挑战是 - Proxy1& Proxy2是通过添加Visual Studio的服务引用命令生成的类。如果我更新服务引用,我的代码更改将消失,每次我将不得不重新编写代码。因此尝试编写代码而不必手动包装这些代理类。

1 个答案:

答案 0 :(得分:2)

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();
    }
}
相关问题