c# - How to keep a class from being instantiated outside of a Factory -


i have factory. not want allow classes factory produces instantiated outside of factory. if make them abstract, static, or give them private constructors won't instantiable @ all! language restriction or what?

i don't want allow this

var awcrap = new extrude2013 (); // bad !!! awcrap.extrudify (); // don't want allow 

rest of code:

using system;  namespace testie {     public enum extrudetype { extrude2013,  extrude2014 }      public interface iextrudestuff {         void extrudify();     }      public class extrude2013 : iextrudestuff {          public void extrudify(){              console.writeline ("extrudify 2013");         }     }      public class extrude2014 : iextrudestuff {          public void extrudify(){              console.writeline ("extrudify 2014");         }     }     public static class extrudefactory {         public static iextrudestuff create(extrudetype t) {             switch (t) {                 case extrudetype.extrude2013: return new extrude2013 ();                 case extrudetype.extrude2014: return new extrude2014 ();                 default: return null;              }          }     }      class mainclass {         public static void main (string[] args) {             // pretty api part             var o = extrudefactory.create (extrudetype.extrude2013);             o.extrudify ();             var p = extrudefactory.create (extrudetype.extrude2014);             p.extrudify ();              var awcrap = new extrude2013 (); // bad !!!             awcrap.extrudify (); // don't want allow         }     } } 

you can't disallow this. whether or not it's language "restriction" matter of opinion, there things consider:

  • make constructor internal. allow type within declaring assembly call constructor, nothing outside assembly. mean code write in assembly responsible calling factory, , means not declare subtypes of class in assembly, since unable call constructor.
  • a similar approach make class expose abstract (or interface), declare internal (or private subclass of factory, since never referenced outside of factory) type implements abstract class or interface.
  • require token factory can provide in constructor. how datatable class works. while constructor still called, user have pass in null value , @ least obvious shouldn't doing this.

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -