Design Pattern How-To: Singleton

Update: this blog has been moved to http://brandonzeider.me/2010/design-patterns/design-pattern-how-to-singleton/

The Singleton Design Pattern is one of the easiest design patterns to understand, and also one of the most useful in my opinion. When done correctly, the singleton pattern ensures that one and only one instance of a class is instantiated. In this post we will cover the singleton pattern, how to make it thread safe, and show a simple implementation. If you are new to design patterns, see my introductory post on the Factory pattern for an explanation.

The singleton pattern is a Creational Pattern that deals with how and when objects are created. They have many uses, and are often found as components in other design patterns. The pattern can be used when only one instance of an object is desired, either out of necessity or for performance reasons. For our example, we will create a class to store common data that can be safely accessed from any class on any thread. Please note that there are many ways to accomplish thread-safety, this post shows a simple, proven method.

Steps

1. Create a private field to store an instance of the class you wish to make a singleton.
2. Create a private static readonly object that will be our locking mechanism (lock statement).
3. Create a single private constructor so that other classes do not use the singleton incorrectly.
4. Create a public static property to access the private field we created in step 1.

That's it. The key is in step 4. Again, there are many ways to ensure thread-safety, but for this example (and my preferred implementation) you lock a static object, check to see if the instance is instantiated, then return the instance. 

Now you can add properties to store data.

Example Implementation

namespace SingletonExample
{
	/// <summary>
	/// Class to store common data. Implemented as a thread-safe Singleton.
	/// </summary>
	public sealed class CommonData
	{
		#region Fields

		private static CommonData _instance = null;
		private static readonly object _lock = new object();

		#endregion Fields

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="CommonData"/> class.
		/// 
		/// A single private constructor to keep other classes from incorrectly 
		/// instantiating this class. 
		/// </summary>
		private CommonData() { }

		#endregion Constructors

		#region Properties

		/// <summary>
		/// Gets the current instance of this class.
		/// </summary>
		/// <value>The current instance of this class.</value>
		public static CommonData Current
		{
			get
			{
				lock (_lock)
				{
					if (_instance == null)
					{
						_instance = new CommonData();
					}

					return _instance;
				}
			}
		}

		/// <summary>
		/// Gets or sets the user ID.
		/// </summary>
		/// <value>The user ID.</value>
		public string UserID { get; set; }

		/// <summary>
		/// Gets or sets the first name.
		/// </summary>
		/// <value>The first name.</value>
		public string FirstName { get; set; }

		/// <summary>
		/// Gets or sets the last name.
		/// </summary>
		/// <value>The last name.</value>
		public string LastName { get; set; }

		#endregion Properties
	}
}

Using the Singleton

CommonData.Current.UserID = "test";
CommonData.Current.FirstName = "Brandon";
CommonData.Current.LastName = "Zeider";

Download

SingletonExample.zip (51.62 kb)

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Design Patterns | Microsoft .NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (0) Post RSSRSS comment feed

Design Pattern How-To: Factory

Update: this blog has been moved to http://brandonzeider.me/2010/design-patterns/design-pattern-how-to-factory/

Design patterns are reusable solutions to common problems in software development. Design patterns have been around for quite some time, but really didn't pick up steam in the software development community until 1994, when the "Gang of Four" (GoF) released Design Patterns: Elements of Reusable Object-Oriented Software. In this book, 23 design patterns are described, grouping them into three categories: Creational, Structural, and Behavioral, and is highly recommended reading for anyone interested in software development.

In this post we will explore one of the most common creational patterns, the Factory. Factories are one attempt to solve the problem of creating objects, where the construction logic is encapsulated in the factory and abstracted from the rest of the system. When class A creates an instance of class B, A and B are tightly coupled via that constructor logic. Factories allow us to remove that coupling. We will cover a simple factory, a more advanced implementation using Generics, and an Abstract Factory. For our examples, we will have a simple use case of Customer and Employee classes that both derive from a User base class. This use case will be overly simplified for the purpose of demonstration.

Simple Factory

Let's say we have a User object with the following definition:

namespace BusinessObjects.Simple
{
	public abstract class User
	{
		public string FirstName { get; set; }

		public string LastName { get; set; }

		public abstract string ID();
	}
}

And the following concrete objects:

namespace BusinessObjects.Simple
{
	public sealed class Employee : User
	{
		public int EmployeeID { get; set; }

		public override string ID() { return "Employee ID: " + EmployeeID; }
	}

	public sealed class Customer : User
	{
		public int CustomerID { get; set; }

		public override string ID() { return "Customer ID: " + CustomerID; }
	}
}

In this example, the Employee and Customer objects are unquely identified by the EmployeeID and CustomerID. Next we can create factories for these objects. First, the base factory, with an abstract method CreateUser. This method must be implemented by concrete factories. Notice that the CreateUser method returns an object of type User, which is the base object for Employee and Customer.

namespace BusinessObjects.Simple.Factories
{
	public abstract class UserFactory
	{
		public abstract User CreateUser(int id);
	}
}

Next, the concrete factories, with the CreateUser implementation. This method encapsulates the constructor logic for that object.

namespace BusinessObjects.Simple.Factories
{
	public sealed class EmployeeFactory : UserFactory
	{
		public override User CreateUser(int id)
		{
			return new Employee()
			{
				EmployeeID = id
			};
		}
	}

	public sealed class CustomerFactory : UserFactory
	{
		public override User CreateUser(int id)
		{
			return new Customer()
			{
				CustomerID = id
			};
		}
	}
}

Now we can test our factories:

private void SimpleFactoryTest()
{
        List<User> users = new List<User>();
        EmployeeFactory employeeFactory = new EmployeeFactory();
        CustomerFactory customerFactory = new CustomerFactory();

        //Create employees
        users.Add(employeeFactory.CreateUser(1));
        users.Add(employeeFactory.CreateUser(2));
        users.Add(employeeFactory.CreateUser(3));
        users.Add(employeeFactory.CreateUser(4));
        users.Add(employeeFactory.CreateUser(5));

        //Create customers
        users.Add(customerFactory.CreateUser(6));
        users.Add(customerFactory.CreateUser(7));
        users.Add(customerFactory.CreateUser(8));
        users.Add(customerFactory.CreateUser(9));
        users.Add(customerFactory.CreateUser(10));

        foreach (User user in users)
        {
                OutputListBox.Items.Add(user.ID());
        }
}

Generics Implementation

With Generics, our implementation takes significantly less code. First, we add constructors to the Customer and Employee objects:

public Customer(int id) { CustomerID = id; }

public Employee(int id) { EmployeeID = id; }

Then we create the generic factory:

namespace BusinessObjects.Generic
{
	public class Factory<T>
	{
		public T Create(params object[] parameters)
		{
			return (T)Activator.CreateInstance(typeof(T), parameters);
		}
	}
}

In this simple example, T represents the type of the object we are instantiating. We then have one method, Create, that accepts a parameter array. Using the Activator class, we create an instance of type T, which calls our constructor on the Customer and Employee objects. That's it! We can then test our factory:

private void GenericFactoryTest()
{
        List<User> users = new List<User>();
        Factory<Employee> employeeFactory = new Factory<Employee>();
        Factory<Customer> customerFactory = new Factory<Customer>();

        //Create employees
        users.Add(employeeFactory.Create(1));
        users.Add(employeeFactory.Create(2));
        users.Add(employeeFactory.Create(3));
        users.Add(employeeFactory.Create(4));
        users.Add(employeeFactory.Create(5));

        //Create customers
        users.Add(customerFactory.Create(6));
        users.Add(customerFactory.Create(7));
        users.Add(customerFactory.Create(8));
        users.Add(customerFactory.Create(9));
        users.Add(customerFactory.Create(10));

        OutputListBox.Items.Add("BEGIN GENERIC TEST");

        foreach (User user in users)
        {
                OutputListBox.Items.Add(user.ID());
        }

        OutputListBox.Items.Add("END GENERIC TEST");
}

Abstract Factory

Abstract factories are much the same as non-abstract factories, but do not use subclasses to determine which class is instantiated. The difference is very subtle, but once you see it in action, it becomes more clear. We'll use the same User, Customer and Employee objects as before. Next we'll create an interface for our factories called IFactory:

namespace BusinessObjects.Abstract
{
	public interface IFactory
	{
		User CreateUser(int id);
	}
}

Next we'll create a CustomerFactory and an EmployeeFactory:

namespace BusinessObjects.Abstract
{
	public class CustomerFactory : IFactory
	{
		#region IFactory Members

		public User CreateUser(int id)
		{
			return new Customer(id);
		}

		#endregion IFactory Members
	}

	public class EmployeeFactory : IFactory
	{
		#region IFactory Members

		public User CreateUser(int id)
		{
			return new Employee(id);
		}

		#endregion IFactory Members
	}
}

Now we're ready to test. This is where the difference between the factory pattern and the abstract factory pattern will become clear.

private void AbstractFactoryTest(bool createEmployee)
{
        IFactory factory = null;

        if (createEmployee)
        {
                factory = new BusinessObjects.Abstract.EmployeeFactory();
        }
        else
        {
                factory = new BusinessObjects.Abstract.CustomerFactory();
        }

        User user = factory.CreateUser(1);

        OutputListBox.Items.Add("BEGIN ABSTRACT TEST");
        OutputListBox.Items.Add(user.ID());
        OutputListBox.Items.Add("END ABSTRACT TEST");
}

In the example above, once the correct factory is determined, we call the CreateUser method defined in the interface, and that returns the correct object without specifying their concrete class.

Summary

As you can see factories are a way of encapsulating class construction and abstracting it from the rest of the system. These examples are very basic, but should give you an idea of how powerful the factory pattern can be. Use them in your project when you want to decouple object creation.

Download

FactoryExample.zip (74.38 kb)

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Design Patterns | Microsoft .NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (2) Post RSSRSS comment feed

WCF Service Call Encapsulation and Abstraction

Update: this blog has been moved to http://brandonzeider.me/2010/microsoft-net/wcf-service-call-encapsulation-and-abstraction/

If you've worked with Windows Communication Foundation (WCF) very long, you know that it's an extremely powerful and flexible platform. Having the ability to consume WCF services in Silverlight makes using Silverlight for your business application much easier. However this does come with a few challenges.

WCF Service Calls Are Asynchronous

All calls to WCF services from Silverlight are asynchronous. This means that to call a service, you must instantiate the generated service client, handle the completed event for the service method you wish to call, call the service method using the generated asynchrouns method, then close the connection using the generated CloseAsync method (which is calling the OnBeginClose method of the ClientBase class).

WCF Service Clients Must Be Explicitly Closed

As mentioned above, after calling a WCF service, you must remember to call the CloseAsync method, otherwise the connection remains open. Even though the generated service client derives from ClientBase, which implements IDisposable, it is not safe to wrap the service client in a using statement and have the IDisposable.Dispose method kill the connection, you must call it explicitly.

Solution

Because of these challenges, and especially if the service is called in more than one class within your Silverlight application (for example more than one viewmodel), you've probably looked for or created a way to encapsulate these service calls and abstract the details of how the service is consumed from the rest of the application. With the aid of generics, we can create a base class that encapsulates the creation of a WCF service client, handling the result of the WCF service call, and closing the connection with IDisposable.

For this example we'll create a simple MathService that allows you to call Add, Subtract, Multiply and Divide. Here's the interface:

using System.ServiceModel;

namespace WcfServiceExample.Web.WCF
{
	[ServiceContract]
	public interface IMathService
	{
		[OperationContract]
		decimal Add(params decimal[] args);

		[OperationContract]
		decimal Multiply(params decimal[] args);

		[OperationContract]
		decimal Subtract(decimal minuend, decimal subtrahend);

		[OperationContract]
		decimal Divide(decimal numerator, decimal denominator);
	}
}

Once our WCF service is working, we can consume this service within our Silverlight application. Within our Silverlight development framework (or wherever you choose), create a base class for all service clients:

using System;
using System.ServiceModel;

namespace Framework.WCF
{
	public abstract class ServiceBase<TClient, TChannel> : ClientBase<TChannel>, IDisposable
		where TClient : ClientBase<TChannel>, new()
		where TChannel : class
	{
		#region Fields
		private readonly TClient _wcfServiceClient = null;
		#endregion Fields

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="ServiceBase<TClient, TChannel>"/> class.
		/// </summary>
		protected ServiceBase()
		{
			_wcfServiceClient = Activator.CreateInstance<TClient>();
		}

		#endregion Constructors

		#region Properties

		/// <summary>
		/// Gets the WCF service client.
		/// </summary>
		/// <value>The WCF service client.</value>
		protected TClient WcfServiceClient { get { return _wcfServiceClient; } }

		#endregion Properties

		#region Methods

		/// <summary>
		/// Handles the result of the WCF service call.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="action">The action.</param>
		/// <param name="result">The result.</param>
		public void HandleResult<T>(Action<T> action, T result)
		{
			if (action != null)
			{
				action(result);
			}
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			if (_wcfServiceClient != null && _wcfServiceClient.State == CommunicationState.Opened)
			{
				try { _wcfServiceClient.InnerChannel.BeginClose(null, null); }
				catch
				{
					_wcfServiceClient.Abort();
					throw;
				}
			}
		}

		#endregion Methods
	}
}

Notice that we are defining the channel and interface with the aid of generics, and closing our connection through the use of IDisposable. Next we can create a concrete class deriving from this base class, passing in the generated service client and interface that we want to abstract.

using System;
using System.Collections.ObjectModel;
using Framework.WCF;

namespace WcfServiceExample.Services
{
	public sealed class MathService : ServiceBase<WebServices.MathService.MathServiceClient, WebServices.MathService.IMathService>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="MathService"/> class.
		/// </summary>
		public MathService()
		{
			base.WcfServiceClient.SubtractCompleted += new EventHandler<WebServices.MathService.SubtractCompletedEventArgs>(WcfServiceClient_SubtractCompleted);
		}

		#endregion Constructors

		#region Methods

		/// <summary>
		/// Encapsulates the call to MathServiceClient.Subtract
		/// </summary>
		/// <param name="callback">The callback.</param>
		/// <param name="minuend">The minuend.</param>
		/// <param name="subtrahend">The subtrahend.</param>
		public void Subtract(Action<decimal> callback, decimal minuend, decimal subtrahend)
		{
			WcfServiceClient.SubtractAsync(minuend, subtrahend, callback);
		}

		/// <summary>
		/// Handles the SubtractCompleted event of the WcfServiceClient control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="WebServices.MathService.SubtractCompletedEventArgs"/> instance containing the event data.</param>
		private void WcfServiceClient_SubtractCompleted(object sender, WebServices.MathService.SubtractCompletedEventArgs e)
		{
			base.HandleResult<decimal>(e.UserState as Action<decimal>, e.Result);
		}

		#endregion Methods
	}
}

Now that we have abstracted MathService, it's ready to be used. Here's where our "hard work" pays off. Instead of calling our WCF service the traditional way:

MathServiceClient mathServiceClient = new MathServiceClient();
mathServiceClient.SubtractCompleted += new System.EventHandler<SubtractCompletedEventArgs>(mathServiceClient_SubtractCompleted);
mathServiceClient.SubtractAsync(SubtractXValue, SubtractYValue);
mathServiceClient.CloseAsync();

We can call it this way:

using (MathService service = new MathService())
{
	service.Subtract(HandleSubtractResult, SubtractXValue, SubtractYValue);
}

This is much cleaner, and our viewmodels do not need to know how the service is created, called, closed, etc. The big win in my book, however, is the ability to use IDisposable to close the service channel connection.

Download

WcfServiceExample.zip (534.83 kb)

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Bookmark and Share dotnetshoutout
Tags: , , , , ,
Categories: Design Patterns | Microsoft .NET | Silverlight | Windows Communication Foundation

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (2) Post RSSRSS comment feed