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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: