4

Factory method is class design pattern. Abstract Factory uses many Factory methods. Why Abstract Factory is object design pattern, not class design pattern? Abstract Factory defer instantiation to which object?

Bood Carley
  • 538
  • 1
  • 4
  • 15

1 Answers1

5

Abstract Factory pattern defers creation of product objects to the ConcreteFactory subclass. Since a client is expecting Factory class (which is the parent of ConcreteFactory subclasses) as a method parameter; based on the instance of ConcreteFactory passed, corresponding product instance is created. So Abstract Factory creates product instances by calling factory methods on a ConcreteFactory instance passed at runtime. Hence this is object design pattern. Typically these Concrete factories are Singletons.

Factory method happens at the class level however. A new ConcreteFactory class has to be created to instantiate a ConcreteProduct. This ConcreteFactory extends Factory class which has a create() method returning Product. ConcreteFactory overrides create() method defined in the Factory parent class.

Aswering the comment:

Yes Factory method is parameterized but in AbstractFactory you will be able to call methods on a ConcreteFactory passed thus enabling you to switch to a different ConcreteFactory at runtime. But in Factory since create() is part of the class, if you want to create concrete products you have to create ConcreteFactory which extends the parent Factory class.

user1168577
  • 1,863
  • 11
  • 14
  • Thanks for your answer. But I think Factory method is also parameterized, and its create() method is also called at run-time. What's wrong with me? Please more explanation. – Bood Carley Jul 03 '12 at 03:04
  • I understand this problem more clearly. May I ask you a question? OK, my question is: Why can't I switch ConcreteFactory in Factory method at run-time? If I create some ConcreteFactory and pass Factory type to methods, so I can switch ConcreteFactory at run-time. – Bood Carley Jul 03 '12 at 03:37
  • 3
    @BoodCarley - I will try to answer your question but let's take a step back. The motivation to apply these patterns is different. In AbstractFactory you want to be able to create multiple families of products but in Factory you are providing hooks for subclasses (Concrete factories) to be able to create ConcreteProduct. – user1168577 Jul 03 '12 at 03:49
  • I know this is an old Q&A but I wanted to ask a similar question and this answer doesn't fully explain it for me. In both patterns, at **runtime** an **instance** of a ConcreteFactory **object** has to be created and can be passed as an abstract base class and used without needing to know at compile time which ConcreteFactory has been created. So why is one a "Class" pattern and the other an "Object" pattern? – Chris Drew Jul 12 '14 at 08:44