开发者

factory method pattern in C#

开发者 https://www.devze.com 2023-02-23 08:47 出处:网络
class A implements IC class B implements IC class Factory has a method GetObject(int x); x=0 for A, x=1 for B.

class A implements IC

class B implements IC

class Factory has a method GetObject(int x); x=0 for A, x=1 for B.

How can I force the usage of Factory.GetObject method to cr开发者_如何转开发eate objects of type A and B and prevent something like new A(), which should be 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()

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.

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...).

0

精彩评论

暂无评论...
验证码 换一张
取 消