Abstract factory design pattern

Sunday, 5 August 2007 13:57 GMT

IN my previous post, I described how to use the Factory Design Pattern and interfaces to create a generic class that instantiate storage objects at run-time as specified in the configuration file of an application.

One of the remarks I received was that the storage object produced by the storage factory class required casting to the correct type.

For example:


	...
	IAccountStorage storage = (IAccountStorage) StorageFactory.GetStorage(typeof(IAccountStorage));
	...

In order to eliminate the cast operation, we need to apply the Abstract Factory Design Pattern which allows factories and their products to be specified without their implementation details. Using an analogy similar to the one in the previous post, this pattern means that we have specifications for factories and specifications for the manufactured products without the actual factories and products themselves.

In programming, this means that factories and classes that they instantiate are specified as interfaces.

For example:


public interface IAccountStorage
{
	void Save(Account account);
}

public interface IAccountStorageFactory
{
	IAccountStorage GetStorage();
}

The actual implementations are based on these interfaces. For example, if we want to build memory-based storage classes, we will have the following code.


public class MemoryAccountStorage
{
	public void Save(Account account)
	{
		// Saves account to memory
	}
}

public class MemoryAccountStorageFactory
{
	public IAccountStorage GetStorage()
	{
		return new MemoryAccountStorage();
	}
}

In the client code, the need for cast is thus eliminated.


	...
	IAccountStorageFactory factory = new MemoryAccountStorageFactory();
	IAccountStorage storage = factory.GetStorage();
	storage.Save(...); // saves an account
	...

Typically, the choice of implementation of IAccountStorageFactory will be done at run-time by a specialised class, based on a configuration setting.

For example:


public static class StorageFactoryHelper
{
	public static IAccountStorageFactory GetAccountStorageFactory()
	{
		Type type = ...; // finds the correct implementation
		IAccountStorageFactory factory = (IAccountStorageFactory) Activator.CreateInstance(type);

		return factory;
	}
}

Note that in this case, since we are using the Activator.CreateInstance method to instantiate an object at run-time, we cannot do without the cast.

Popularity: 46% [?]

Add a comment

Possibly related:



« Newer

Powered by WordPress and Eddy Young.

DISCLAIMER: This site is supported by advertising. As a result, cookies may be installed by advertisers in order to track usage and trends. If you do not want this, please disable cookies for this site.