Showing posts with label Design. Show all posts
Showing posts with label Design. Show all posts

Monday, 30 January 2012

Abstract Factory vs Factory

There are numerous post out there to explain the differences - i just wanted to add on

Factory - encapsulates the logic of creating a concrete type
Abstract Factory - encapsulates grouping of related factories.

I always start with Factory pattern first to decouple the creation logic from client.
So when will we go for Abstract Factory - as soon as your factory method violates Open/Closed principle. If your Factory method contains lots of 'if/else' or 'switch' statements, then it is time to move onto Abstract Factory. Please refer this article.

Also DBProviderFactory is another example of AF pattern. SqlClientFactory, OracleClientFactory, OleDbFactory are all grouped under DBProviderFactory.

http://en.wikipedia.org/wiki/Abstract_factory_pattern
http://en.wikipedia.org/wiki/Factory_object
http://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.80%29.aspx


Thursday, 10 November 2011

Idea1 - Avoid Switch/If conditions

While developing a web service, i came across a scenario where i need to create a Factory pattern to instantiate a Response class based on the Request string.

For example, if the Request is 'AuthenticateUserRequest', i need to create 'AuthenticateUserResponse'.

So i started writing an switch case like below

switch(requestName)
{
case "AuthenticateUserRequest":
return new AuthenticateUserResponse();
}

soon the method grows big, and i wanted to avoid this.

so i declared an dictionary with key value pair, with key being the request name and value being the response being the corresponding response class.

so it becomes

Dictionary responses = new Dictionary
{
{"AuthenticateUserRequest", new AuthenticateUserResponse()},
{"CreateOrderRequest", new CreateOrderResponse() }
};

-----
return responses[requestName].value.Clone();