Search code examples
c#factoryclass-visibility

Class instance creation restrictions


I have many algorithm classes that implement the same interface; another "factory" class has the responsibility to instantiate the correct algorithm class through a config param, then call the start method on that instance.

I would like to restrict the the visibility of the constructor (or any other instance creation mechanism) of the algorithm classes to the factory class only.

How can I solve this? The only clean solution I can think about is to move those classes in a different .dll and change algorithm classes to private, but that's not what I want to do right now.


Solution

  • Maybe you will be satisfied by the following sample (yes, I know what reflection shouldn't be used normally...)

    public class Algorithm
    {
        private Algorithm()
        {
        }
    
        public void SomeMethod()
        {
        }
    }
    
    public static class Factory
    {
        public static Algorithm Create()
        {
            var constructor = typeof(Algorithm).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
            return (Algorithm)constructor.Invoke(null);
        }
    }
    

    Here you can create instance of Algorithm via Factory.Create, not by new Algorithm.