#948 – Using Generic Lazy Class to Implement the Singleton Pattern

The singleton pattern is useful in cases when you only want/need a single instance of a type, e.g. to use in creating instances of some other type (an object factory).

We can make use of the Lazy<T> type to implement a singleton that is created as late as possible, i.e. just before it is used.

    public sealed class DogFactory
    {
        // Instance created when first referenced
        private static readonly Lazy<DogFactory> instance =
            new Lazy<DogFactory>(() => new DogFactory());

        // Prevent instantiation
        private DogFactory() { }

        public static DogFactory Instance
        {
            get { return instance.Value; }
        }

        // Actual methods go here, e.g.:
        public Dog CreateDog(string name)
        {
            return new Dog(name);
        }
    }

Notice that we can access other static members of the DogFactory without forcing the instance object to get created. The instance will only be instantiated when we use the Instance property.

Advertisement

#823 – A Nested Factory Class Implemented as a Singleton

Below is an instance of the factory pattern, with the factory class nested within the class that it creates instances for, implemented as a singleton.

    public class Dog
    {
        public string Name { get; set; }

        private Dog(string name)
        {
            Name = name;
        }

        public class Factory
        {
            // Instance created when first referenced
            private static readonly Factory instance = new Factory();

            // Prevent early instantiation due to beforefieldinit flag
            static Factory() { }

            // Prevent instantiation
            private Factory() { }

            public static Factory Instance
            {
                get { return instance; }
            }

            // Factory method
            public Dog CreateDog(string name)
            {
                return new Dog(name);
            }
        }
    }

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

#821 – The Factory Pattern

Factory is a design pattern that you can use when you don’t want client code creating objects directly, but you want to centralize object creation within another class.  To get a new instance of an object, you call a method in the factory, which creates the object on your behalf.

In the example below, DogFactory.CreateDog is a factory method, which does the actual creation of a Dog object.

    public sealed class DogFactory
    {
        // Instance created when first referenced
        private static readonly DogFactory instance = new DogFactory();

        // Prevent early instantiation due to beforefieldinit flag
        static DogFactory() { }

        // Prevent instantiation
        private DogFactory() { }

        public static DogFactory Instance
        {
            get { return instance; }
        }

        // Factory pattern - method for creating a dog
        public Dog CreateDog(string name, int age)
        {
            return new Dog(name, age);
        }
    }

To create a Dog:

            Dog myDog = DogFactory.Instance.CreateDog("Kirby", 15);

#794 – A Better INotifyPropertyChanged Implementation

When implementing INotifyPropertyChanged, you need to pass the property name as a string in the PropertyChangedEventArgs object.  This can lead to subtle bugs in your code.  If you happen to spell the property name wrong, the client will be notified about the wrong (non-existent) property and the compiler won’t warn you that there is a problem.

If you use C# 5.0 and target the .NET Framework 4.5, there’s an easier way.  You can use the CallerMemberName attribute to avoid having to pass the property name as a string.

        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                if (age != value)
                {
                    age = value;
                    RaisePropertyChanged();
                }
            }
        }

        //-- INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged([CallerMemberName]string prop = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }

Don’t forget to include:

using System.Runtime.CompilerServices;

#793 – Being Notified When an Object’s Properties Change, Part II

Once you’ve implemented the INotifyPropertyChanged interface in a class, you can subscribe to the PropertyChanged event for an instance of your class.  Assuming that you’ve implemented INotifyPropertyChanged properly, the event will fire whenever any property value in the object changes.

The code below assumes that the Dog class implements INotifyPropertyChanged.

        static void Main(string[] args)
        {
            Dog d = new Dog("Bob", 5);

            d.PropertyChanged += d_PropertyChanged;

            d.Name = "Bob Jr.";
            d.AgeThisDog();
            d.Age = 10;
        }

        static void d_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Console.WriteLine(string.Format("Property {0} just changed", e.PropertyName));
        }

793-001

The PropertyChanged event handler receives an instance of a PropertyChangedEventArgs object, which just contains a PropertyName property that tells you which property changed.  It pass any information about either the old or the new values of the property.  The assumption is that client code can read the updated property value on their own.

#792 – Being Notified When an Object’s Properties Change, Part I

If you write a class, there’s a pattern that you can implement, to let users of your class know when a property value changes.  This pattern is implemented by implementing the INotifyPropertyChanged in your class.

The purpose of this pattern is to let client code know that some property value has changed, in situations where that code didn’t initiate the change.  For example, this pattern is used in data binding.

Below is an example of a class that implements INotifyPropertyChanged.  The class defines an event that is fired whenever any property value changes.

    public class Dog : INotifyPropertyChanged
    {
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    RaisePropertyChanged("Name");
                }
            }
        }

        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                if (age != value)
                {
                    age = value;
                    RaisePropertyChanged("Age");
                }
            }
        }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void AgeThisDog()
        {
            Age++;
        }

        //-- INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string prop)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

Part II of this topic will show how client code can use this new event.

#786 – A Lazier Singleton Pattern

Ideally, you’d want the implementation of a singleton to be as “lazy” as possible, i.e.–create the instance as late as possible, just prior to when you need it.  This helps performance, since we only create the object if/when we need it.

In our earlier implementation, the instance of our class gets created whenever any of the static members of our class are accessed.  This might be when we first access the Instance property, but might be earlier, if we had other static members in the class.

Below is a Singleton pattern that is a bit lazier.

    public sealed class DogFactory
    {
        // Prevent instantiation
        private DogFactory() { }

        public static DogFactory Instance
        {
            get { return InstanceContainer.instance; }
        }

        private class InstanceContainer
        {
            // Prevent early instantiation due to beforefieldinit flag
            static InstanceContainer() { }

            internal static readonly DogFactory instance = new DogFactory();
        }
    }

#785 – The Singleton Pattern

Singleton is a design pattern that you can use when you have a situation where you want to limit a particular class to have at most one instance.

A singleton behaves similarly to a static class in C#, but has some advantages, in that it behaves as a traditional object.  (E.g. Can implement an interface, or be passed to a method).

Here’s a common (thread-safe) pattern for implementing a singleton in C#.

    public sealed class DogFactory
    {
        // Instance created when first referenced
        private static readonly DogFactory instance = new DogFactory();

        // Prevent early instantiation due to beforefieldinit flag
        static DogFactory() { }

        // Prevent instantiation
        private DogFactory() { }

        public static DogFactory Instance
        {
            get { return instance; }
        }

        // Actual methods go here, e.g.:
        public Dog CreateDog(string name)
        {
            return new Dog(name);
        }
    }

To use the singleton, you use the Instance property:

            Dog d = DogFactory.Instance.CreateDog("Bob");