#822 – Embed a Factory Class Inside Its Related Class

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");

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #822 – Embed a Factory Class Inside Its Related Class

  1. Pingback: Dew Drop – April 15, 2013 (#1,527) | Alvin Ashcraft's Morning Dew

Leave a comment