Search code examples
.netdesign-patternsfactorypublic-method

Factory Method pattern and public constructor


Im making a factory method that returns new instances of my objects. I would like to prevent anyone using my code from using a public constructor on my objects. Is there any way of doing this?

How is this typically accomplished:

public abstract class CarFactory
{
  public abstract ICar CreateSUV();
}

public class MercedesFactory : CarFactory
{
  public override ICar CreateSUV()
  {
    return new Mercedes4WD();
  }
}

I then would like to limit/prevent the other developers (including me in a few months) from making an instance of Mercedes4WD. But make them call my factory method. How to?


Solution

  • you can make the class Mercedes4WD a internal class with an internal constructor which will stop it being instantiated from outside of the library which contains the factory.

    You might be better having a factory method on your class which produces the instance, which you could call from your factory class, but that is not that different from just 'newing' it up.

    You could also have the Mercedes4WD on one assembly, the factory in another and your code in a third, then the factory assembly could be a friend of the Mercedes4WD assembly so it could create the instances, but the main code would not be so it couldn't. That would reduce the scope under which the instances could be created, but everything would a bit more complex.

    Really you need to provide some more information. when you say you would like to stop people constructing later, are you talking about other devs working in the same codebase? If so there is not really that much you can do. You might be able to do some checking in the constructor to see if the next method up in the stack is the factory's method and throw an exception if not, but I'm not sure that is a great idea...

    The real question is why do you want to do this?