Coding by Design Patterns – Abstract Factory Pattern
The Abstract Factory Pattern provides an interface for allowing classes to control creation of their aggregated objects without the client class having to know the details associated with each object family.
The example I’ve used in code is just something I was started playing with myself but didn’t get round to actually finishing off. It was going to be an application to allow a user to see all their data feeds from social media (LinkedIn/Twitter etc) in a single application. Its very much simplified here but gives the basic structure ond understanding of the abstract factory.
The first thing required is the factory interface, this will determine what aggregate objects require creation.
public interface SocialConnectorFactory
{
IAuthetication CreateAuthentication();
INewsList CreateNewsList();
}
Once we have that we can create the individual connectors.
public class TwitterFollower : SocialConnectorFactory
{
public IAuthetication CreateAuthentication()
{
throw new NotImplementedException();
}
public INewsList CreateNewsList()
{
throw new NotImplementedException();
}
}
Then it is just a case of creating the factory client. I wont worry about writing out the IAuthetication and INewsList interfaces and derived classes as it doesnt really matter in this instance.
public class ConnectorClient<T> where T : SocialConnectorFactory, new()
{
IAuthetication _auth;
INewsList _news;
T _factory;
public ConnectorClient()
{
_factory = new T();
_auth = _factory.CreateAuthentication();
_news = _factory.CreateNewsList();
}
public IEnumerable<string> GetNewsStream()
{
return _news.GetNewsItems(_auth);
}
}
The usefulness of this type of factory is obvios when it comes to using it, to get the news stream from any connector that has been implemented it just needs 2 simple lines of code.
ConnectorClient<TwitterFollower> news = new ConnectorClient<TwitterFollower>(); var stream = news.GetNewsStream();

No trackbacks yet.