简体   繁体   English

C#中的工厂方法模式

[英]factory method pattern in C#

class A implements IC class A工具IC
class B implements IC class B实现IC

class Factory has a method GetObject(int x) ; class Factory有一个方法GetObject(int x) x=0 for A , x=1 for B . x=0Ax=1B

How can I force the usage of Factory.GetObject method to create objects of type A and B and prevent something like new A() , which should be Factory.GetObject(0) ? 如何强制使用Factory.GetObject方法创建类型为AB对象,并防止诸如new A()之类A东西应为Factory.GetObject(0)

How can I force the usage of Factory GetObject method to create objects of type A and B and prevent something like new A() 如何强制使用Factory GetObject方法创建类型为A和B的对象并防止出现类似new A()的问题

You can't force the usage of Factory.GetObject , this is something that you should write in the documentation of the API you are providing after marking A and B constructors internal. 您不能强制使用Factory.GetObject ,这是在将A和B构造函数标记为内部之后,应该在提供的API文档中编写的内容。

public class A: IC
{
    internal A() { }
}

public class B: IC
{
    internal B() { }
}

public static class Factory
{
    public static IC GetObject(int x)
    {
        if (x == 0)
        {
            return new A();
        }

        if (x == 1)
        {
            return new B();
        }

        throw new ArgumentException("x must be 1 or 2", "x");
    }
}

This way those constructors will not be accessible from other assemblies. 这样,将无法从其他程序集中访问这些构造函数。 Also don't forget about Reflection which will allow for direct instantiation of those classes no matter how hard you try to hide them. 也不要忘记反射,无论您尝试隐藏它们的程度如何,都可以直接实例化这些类。

I'm not sure if it's still relevant (it's been a year...) but here's how you can achieve further enforcement of the factory usage: 我不确定它是否仍然有用(已经一年了……),但是这是您可以进一步实施工厂用法的方法:

public class A
{
   internal protected A() {}
}

public class AFactory
{
   public A CreateA()
   {
      return new InternalA();
   }

   private class InternalA : A
   {
      public InternalA(): base() {}
   }
}

Components using class A cannot directly create it (so long they don't inherit it...). 使用类A的组件无法直接创建它(只要它们不继承它...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM