2

I am learning factory method design pattern now, before that I learned simple factory pattern. I thought simple factory is useful because it transfer the if/else control flow to factory so the purity of product can be reserved. And then I learned factory method pattern, and I thought it is complex and beautiful.

However, it occurred to me that there are no if/else control flow in factory method pattern any more, client know which product it will use and client choose corresponding factory. For example

Factory factory = new SpecificFactory;
Product product = new SpecificProduct;

well, since client know which product they want to use(no if/else control), why just simple new SpecificProduct why need extra factory?

I searched for it but didn't find satisfying answer.
In fact, what I want to ask is like Why do we need Abstract factory design pattern? except for this one is factory method not abstract factory.

Community
  • 1
  • 1
vincent chou
  • 91
  • 2
  • 8
  • Still, you want your product Initialization to be encapsulated only in one place. the initialization may be much more than just calling the Constructor of the SpecificProduct class. – Erez May 04 '14 at 09:33
  • You don't need it until you'll need it. No answer makes much sense until you have the problem. Then you'll discover that your solution is actually a design pattern. – MikeSW May 04 '14 at 16:07

1 Answers1

0

The Intent defined for this pattern in the GoF book is

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

There is still a conditional choice, but it's hidden in the client's inheritance structure.

The example used in the motivation section is of a framework for applications that can present multiple documents to the user.

In this example, there are two abstract classes Application and Document, which are subclassed as appropriate to (for instance) DrawingApplication and DrawingDocument. DrawingApplication knows any document it creates should be a DrawingDocument, but the superclass Application doesn't. So CreateDocument is made an abstract method in Application and implemented in subclasses to create the appropriate type of document.

Don Roby
  • 40,677
  • 6
  • 91
  • 113