What is difference between Factory and Abstract Factory ?
What is difference between Factory and Abstract Factory design pattern? How to decide which design pattern to use? What is checklist to decide design pattern?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Abhay ShankerPosted May 20, 2014, 11:26 PM
http://architects.dzone.com/articles/factory-method-vs-abstract
http://www.dofactory.com/topic/1449/what-is-the-difference-between-abstract-factory-and-factory-design-pattern/1623.aspx#p1623
The Factory Method is usually categorised by a switch statement where each case returns a different class, using the same root interface so that the calling code never needs to make decisions about the implementation.
Think of a credit card validator factory which returns a different validator for each card type.
public ICardValidator GetCardValidator (string cardType)
{
switch (cardType.ToLower())
{
case "visa":
return new VisaCardValidator();
case "mastercard":
case "ecmc":
return new MastercardValidator();
default:
throw new CreditCardTypeException("Do not recognise this type");
}
}
The Abstract Factory is where you have multiple concrete factory classes (not Factory Methods) derived from one interface which may return many different types from different methods.
Think of a chess game manager with a different class for each set of variant rules.
public class StandardChessRulesFactory : IChessRulesFactory
{
public IBoardMapper GetBoardMapper()
{
return new StandardChessBoardMapper();
}
public IKingMover GetKingMover()
{
return new StandardChessKingMover();
}
public IMoveClock GetMoveClock()
{
return new StandardMoveClock();
}
}
public class HexagonalChessRulesFactory : IChessRulesFactory
{
public IBoardMapper GetBoardMapper()
{
return new HexagonalChessBoardMapper();
}
public IKingMover GetKingMover()
{
return new HexagonalChessKingMover();
}
public IMoveClock GetMoveClock()
{
return new StandardMoveClock();
}
}
public class SpeedChessRulesFactory : IChessRulesFactory
{
public IBoardMapper GetBoardMapper()
{
return new StandardChessBoardMapper();
}
public IKingMover GetKingMover()
{
return new StandardChessKingMover();
}
public IMoveClock GetMoveClock()
{
return new SpeedChessMoveClock();
}
}
An Abstract Factory, much like a Strategy, is often selected using a Factory Method, but it isn't necessary to combine them so it is its own pattern.