0% found this document useful (0 votes)
41 views

Factory Method Pattern

The Factory Method pattern provides an interface for creating objects in a superclass, but allows subclasses to decide which class to instantiate. This allows subclasses to vary the type of objects created. For example, a VehicleDriver class could have a getVehicle() method that subclasses like CarDriver and BusDriver override to return different Vehicle types like Car and Bus. The pattern introduces separation between an application and product classes, providing flexibility to vary products without code changes.

Uploaded by

ali abbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Factory Method Pattern

The Factory Method pattern provides an interface for creating objects in a superclass, but allows subclasses to decide which class to instantiate. This allows subclasses to vary the type of objects created. For example, a VehicleDriver class could have a getVehicle() method that subclasses like CarDriver and BusDriver override to return different Vehicle types like Car and Bus. The pattern introduces separation between an application and product classes, providing flexibility to vary products without code changes.

Uploaded by

ali abbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Factory Method Pattern | Creational

Intent:
Defines an interface for creating an object, but lets subclasses decide which class to
instantiate. Factory Method lets a class defer instantiation to subclasses.
Also Known As:
Virtual Constructor
Motivation:
Take into consideration a framework for desktop applications. Such applications are meant
to work with documents. A framework for desktop applications contains definitions for
operations such as opening, creating and saving a document.
The basic classes are abstract ones, named Application and Document, their clients having
to create subclasses from them in order to define their own applications.
For generating a drawing application, for example, they need to define the
DrawingApplication and DrawingDocument classes. The Application class has the task of
managing the documents, taking action at the request of the client (for example, when the
user selects the open or save command form the menu).
Because the Document class that needs to be instantiated is specific to the application, the
Application class does not know it in advance, so it doesn’t know what to instantiate, but it
does know when to instantiate it. The framework needs to instantiate a certain class, but it
only knows abstract classes that can’t be instantiated.
The Factory Method design pattern solves the problem by putting all the information related
to the class that needs to be instantiated into an object and using them outside the
framework, as you can see below:

Applicability:
1. A class can’t anticipate the class of objects it must create.
2. A class wants its sub classes to specify the objects it creates.
3. Classes delegate responsibility to one of several helper subclasses.
Structure:
Participants:
The classes that take part in Factory Method pattern are:
Product: Defines the interface of objects the factory method creates.
ConcreteProduct: Implements the Product interface.
Creator: Declares the factory method, which returns an object of the type Product. Creator
may also provide a default implementation of the factory method which returns a
default ConcreteProduct object.
ConcreteCreator: Overrides the factory method to return an instance of a ConcreteProduct.
Collaborations:
Creator relies on its subclasses to provide an implementation for the factory method so that
it returns an instance of the appropriate ConcreteProductclass.
Consequences:
The benefits and drawbacks of factory method pattern are as follows:
• The main reason for which the factory pattern is used is that it introduces a
separation between the application and a family of classes (it introduces weak
coupling instead of tight coupling hiding concrete classes from the application). It
provides a simple way of extending the family of products with minor changes in
application code.
• It provides customization hooks. When the objects are created directly inside the
class it’s hard to replace them by objects which extend their functionality. If a factory
is used instead to create a family of objects the customized objects can easily
replace the original objects, configuring the factory to create them.
• The factory has to be used for a family of objects. If the classes doesn’t extend
common base class or interface they cannot be used in a factory design template.
Implementation:
All concrete products are subclasses of the Product class, so all of them have the same
basic implementation, at some extent. The Creator class specifies all standard and generic
behavior of the products and when a new product is needed, it sends the creation details
that are supplied by the client to the ConcreteCreator.
Having this diagram in mind, it is easy for us now to produce the code related to it. Here is
how the implementation of the classic Factory method should look:
1 public interface Product { }
2
3 public class ConcreteProduct implements Product { }
4
5 public abstract class Creator
6 {
7 public void anOperation()
8 {
9 Product product = factoryMethod();
10 }
11 protected abstract Product factoryMethod();
12 }
13
14 public class ConcreteCreator extends Creator
15 {
16 protected Product factoryMethod()
17 {
18 return new ConcreteProduct();
19 }
20 }
21
22 public class Client
23 {
24 public static void main( String arg[] )
25 {
26 Creator creator = new ConcreteCreator();
27 creator.anOperation();
28 }
29 }

Sample Code:
Let’s consider a Vehicle interface and 2 of its implementations namely Car and Vehicle:
1 interface Vehicle
2 {
3 public void drive();
4 public void clean();
5 }
6
7 class Car implements Vehicle
8 {
9 @Override
10 public void drive()
11 {
12 System.out.println("Driving a car...");
13 }
14 @Override
15 public void clean()
16 {
17 System.out.println("Cleaning a car...");
18 }
19 }
20
21 class Bus implements Vehicle
22 {
23 @Override
24 public void drive()
25 {
26 System.out.println("Driving a Bus...");
27 }
28 @Override
29 public void clean()
30 {
31 System.out.println("Cleaning a Bus...");
32 }
33 }
And to drive() and clean() the Vehicle we would use a VehicleDriver.

Let’s consider the implementation and of VehicleDriver:


?
1 abstract class VehicleDriver
2 {
3 public abstract Vehicle getVehicle();
4 public void driveVehicle()
5 {
6 getVehicle().drive();
7 }
8 public void cleanVehicle()
9 {
10 getVehicle().clean();
11 }
12 }
13
14 class CarDriver extends VehicleDriver
15 {
16 @Override
17 public Vehicle getVehicle()
18 {
19 return new Car();
20 }
21 }
22
23 class BusDriver extends VehicleDriver
24 {
25 @Override
26 public Vehicle getVehicle()
27 {
28 return new Bus();
29 }
30 }

In the above VehicleDriver implementation the getVehicle() method is the factory method
which is overridden by the CarDriver and Busdriver to return Car and Businstances
respectively. In this way the programmer would be more concerned about using
the VehicleDriver abstraction and need not be concerned about its different implementations.

Known Uses:
1. Class View in the Smalltalk-80 Model/View/Controller framework has a method
defaultController that creates a controller, and this might appear to be a factory
method. But subclasses of View specify the class of their default controller by
defining defaultControllerClass, which returns the class from which defaultController
creates instances. So defaultControllerClass is the real factory method, that is, the
method that subclasses should override.
2. In Smalltalk-80 the factory method parserClass defined by Behavior (a superclass of
all objects representing classes). This enables a class to use a customized parser for
its source code.
3. The Orbix ORB system from IONA Technologies uses Factory Method to generate
an appropriate type of proxy when an object requests a reference to a remote object.
Related Patterns:
• Abstract Factory is often implemented with factory methods.
• Factory methods are usually called within Template Methods. In the Document
example above, NewDocument() is a template method.
• Prototypes don’t require subclassing Creator. Instead, they often require an Initialize
operation on the product class. Factory Method doesn’t require such operation.
Example Factory Method classes in java API:
java.util.Calendar
java.util.ResourceBundle
java.text.NumberFormat
java.nio.charset.Charset
java.net.URLStreamHandlerFactory
Non-software example:
The Factory Method defines an interface for creating objects, but lets subclasses decide
which classes to instantiate. Injection molding presses demonstrate this pattern.
Manufacturers of plastic toys process plastic molding powder, and inject the plastic into
molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the
mold.

You might also like