Quantcast
Channel: What are the differences between Abstract Factory and Factory design patterns? - Stack Overflow
Viewing all articles
Browse latest Browse all 22

Answer by jgauffin for What are the differences between Abstract Factory and Factory design patterns?

$
0
0

Abstract factory creates a base class with abstract methods defining methods for the objects that should be created. Each factory class which derives the base class can create their own implementation of each object type.

enter image description here

Factory method is just a simple method used to create objects in a class. It's usually added in the aggregate root (The Order class has a method called CreateOrderLine)

enter image description here

Abstract factory

In the example below we design an interface so that we can decouple queue creation from a messaging system and can therefore create implementations for different queue systems without having to change the code base.

interface IMessageQueueFactory{  IMessageQueue CreateOutboundQueue(string name);  IMessageQueue CreateReplyQueue(string name);}public class AzureServiceBusQueueFactory : IMessageQueueFactory{      IMessageQueue CreateOutboundQueue(string name)      {           //init queue           return new AzureMessageQueue(/*....*/);      }      IMessageQueue CreateReplyQueue(string name)      {           //init response queue           return new AzureResponseMessageQueue(/*....*/);      }}public class MsmqFactory : IMessageQueueFactory{      IMessageQueue CreateOutboundQueue(string name)      {           //init queue           return new MsmqMessageQueue(/*....*/);      }      IMessageQueue CreateReplyQueue(string name)      {           //init response queue           return new MsmqResponseMessageQueue(/*....*/);      }}

Factory method

The problem in HTTP servers is that we always need an response for every request.

public interface IHttpRequest{    // .. all other methods ..    IHttpResponse CreateResponse(int httpStatusCode);}

Without the factory method, the HTTP server users (i.e. programmers) would be forced to use implementation specific classes which defeat the purpose of the IHttpRequest interface.

Therefore we introduce the factory method so that the creation of the response class also is abstracted away.

Summary

The difference is that the intended purpose of the class containing a factory method is not to create objects, while an abstract factory should only be used to create objects.

One should take care when using factory methods since it's easy to break the LSP (Liskov Substitution principle) when creating objects.


Viewing all articles
Browse latest Browse all 22

Trending Articles