GofPatterns Gofpatterns  





Creational Patterns  «Prev  Next»
Lesson 6 Factory Method: structure
Objective Develop the subclasses for the Vehicle Class.
Factory Methods are most common when programmers know at compile time that they need to instantiate an instance of a subclass of a common base class but they do not know which concrete subclass to instantiate. For example, they know the Vehicle class but not the Car, Truck, or Bicycle subclasses.
The Factory Method pattern defers the decision of which subclass to instantiate to happen at runtime.
The Factory Method pattern has several variations. What unites them all is that a nonconstructor method creates instances of a class. The main variant of the Factory Method uses an abstract Creator class to create instances of an abstract Product class. Concrete subclasses of the Creator class create particular concrete instances of the Product class.
Diagram of Factory Method structure
Factory Method uses an abstract Creator class to create instances of an abstract Product class
Clients see only the two abstract classes "above the water line."
There may in fact be many different classes below the water line, but client programmers never see them.

Parameterized Factory Method
Another popular variation is called the parameterized Factory Method. This uses a single, generally concrete, Creator class with a single Factory Method to create instances of different subclasses. The subclass instantiated is chosen based on the arguments passed to the Factory Method. The openConnection() method of java.net.URL is an example of a parameterized Factory Method.
Diagram of the Factory Method using parameterized Factory Method
Diagram of the Factory Method using parameterized Factory Method
Concrete Subclasses - Exercise
In this exercise, you will write four subclasses for the Vehicle class.
Concrete Subclasses - Exercise