#822 – Embed a Factory Class Inside Its Related Class
April 15, 2013 1 Comment
You can use the factory pattern when you want to centralize object creation within a class different from the one representing the object being created.
One problem with making the factory class independent is that the constructor in the main class still needs to be public, which allows the factory to create an object. Other code can then circumvent the factory, creating the object directly.
One solution is to make the factory class a nested type within the main class and then make the constructor of the main class private.
public class Dog { public string Name { get; set; } private Dog(string name) { Name = name; } public class Factory { // Factory pattern - method for creating a dog public static Dog CreateDog(string name) { return new Dog(name); } } }
To create an instance of the object:
// Create a dog Dog myDog = Dog.Factory.CreateDog("Kirby");