advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorial: Manufacturing Java Objects with the Factory Method Design Pattern:

The Factory Method Pattern

According to the GoF book, the Factory Method design pattern "Defines an interface for creating an object, but lets the subclasses decide which to instantiate. Factory Method lets a class defer instantiation to subclasses." The Factory Methods is also known as a "virtual constructor" because of this unique attribute of allowing subclasses to "decide" which concrete class to instantiate.

Motivation

The Factory Method design pattern is for situations in which
  • You need to instantiate a particular object from a pool of related objects.
  • Until runtime, you don't know which of the pool's objects to instantiate.
Consider an application for ordering a car. You don't know which car object to instantiate until the user selects a particular make and model. So how do you write the code? This is a clumsy way to write the code:
public class OrderCars
	{
	public Car orderCar(String model)
		{
		Car car;
		if(model.equals("Lucerne"))
			car = new Buick(model);
		else if(model.equals("Corvette"))
			car = new Chevrolet(model);
		else if(model.equals("Fusion"))
			car = new Ford(model);
		else if(model.equals("GTO"))
			car = new Pontiac(model);
		else if(model.equals("Vue"))
			car = new Saturn(model);

		car.buildCar();
		car.testCar();
		car.shipCar();
		}
	}
The OrderCars class defines a method, orderCar(). This orderCar() method gets the job done. But the section of code containing the conditionals will change as you add or delete car makes and models. The rest of the code (building, testing, and shipping a car) does not change.

The GoF book tells you to "Identify the aspects of your application that vary and separate them from what stays the same." But the above code is an inconvenient mix—a mix of changing and (relatively) unchanging code. Another way to think about this issue is to notice the mix of specific and general code. While the first part of refers to Lucernes, Buicks, and Corvettes, the second part of the code refers to car—a reference to any Car instance.

What's the best way to partition the code into its changing and unchanging parts (into its specific and general parts)? In this scenario, the word "best" has several meanings:

  • What's most versatile in terms of future development and maintenance?
  • What's most easily recognizable by other developers (by virtue of its being a well-known pattern)?

UML Diagram

Figure 1 shows the official UML diagram for the Factory Method pattern.


Figure 1: The UML diagram for the Factory Method design pattern.

The diagram contains four classes:

  • The Creator abstract class declares an abstract factoryMethod() method that returns an instance of Product or ConcreteProduct.
  • The ConcreteCreator class extends the Creator class. This Creator class implements the abstract factoryMethod() method.
  • The Product abstract class declares a product that's produced by a particular Creator factory.
  • The ConcreteProduct class extends the Product class to define all the similar objects that can be instantiated at any given time within the application. In the car ordering application, the concrete products are Buick, Chevrolet, Ford, Pontiac, Saturn, and others that can be defined.

Using the Factory Method

Figure 2 shows a Factory Method UML diagram that's specific to the car ordering application:


Figure 2: The UML diagram for the car ordering application.

The source code for the diagram of Figure 2 is in Listings 1 to 6. The classes of the concrete products (Buick, Chevrolet, etc.) are all very similar. For the sake of brevity, only two of them appear in these listings.

In Listings 1 through 6, notice the clean division between general and specific code. The two abstract classes (Car and CarFactory) contain all the general code and the concrete classes (FordFactory, Buick, and so on) contain all code specific to particular makes and models.

The code below shows the client application. The application starts by creating instances of GeneralMotorsFactory and FordFactory. Other defined factories could be instantiated here as well. Each concrete class (GeneralMotorsFactory, FordFactory, etc.) has its own createCar() method, and shares an orderCar() method with the other concrete classes (the orderCar() method comes from the abstract CarFactory base class).

public class OrderCars
	{
	public static void main(String[] args)
		{
		CarFactory gmfactory = new GeneralMotorsFactory();
		CarFactory fordfactory = new FordFactory();

		gmfactory.orderCar("Pontiac","GTO");
		fordfactory.orderCar("Mercury","Mark IV");
		gmfactory.orderCar("Saturn","Vue");
		fordfactory.orderCar("Ford","Fusion");
		gmfactory.orderCar("Chevrolet","Corvette");
		gmfactory.orderCar("Buick","Lucerne");
		}
	}
The orderCar() method (defined in the CarFactory base class) has parameters "Pontiac" and "GTO". The code inside the orderCar() method creates a new car by calling the appropriate version of createCar(). In the "Pontiac","GTO" case, the appropriate createCar() version is the one defined in the GeneralMotorsFactory class. The GeneralMotorsFactory class encapsulates the conditionals that can change with new makes and models.

The Pontiac class assigns the appropriate values to the make, model, and manufacturer variables. Then the orderCar() method calls the buildCar(), testCar(), and shipCar() methods to fulfill the order. The above code builds the remaining cars in a similar fashion using the factories in Listings 1, 2, and 3. Figure 3 shows the output of the car ordering application.

--- Fulfilling the order for a Pontiac GTO ---
Building the Pontiac GTO at the General Motors factory...
Testing the Pontiac GTO at the General Motors test track...
Shipping the Pontiac GTO at the Pontiac dealership...

--- Fulfilling the order for a Mercury Mark IV ---
Building the Mercury Mark IV at the Ford factory...
Testing the Mercury Mark IV at the Ford test track...
Shipping the Mercury Mark IV at the Mercury dealership...

--- Fulfilling the order for a Saturn Vue ---
Building the Saturn Vue at the General Motors factory...
Testing the Saturn Vue at the General Motors test track...
Shipping the Saturn Vue at the Saturn dealership...

--- Fulfilling the order for a Ford Fusion ---
Building the Ford Fusion at the Ford factory...
Testing the Ford Fusion at the Ford test track...
Shipping the Ford Fusion at the Ford dealership...

--- Fulfilling the order for a Chevrolet Corvette ---
Building the Chevrolet Corvette at the General Motors factory...
Testing the Chevrolet Corvette at the General Motors test track...
Shipping the Chevrolet Corvette at the Chevrolet dealership...

--- Fulfilling the order for a Buick Lucerne ---
Building the Buick Lucerne at the General Motors factory...
Testing the Buick Lucerne at the General Motors test track...
Shipping the Buick Lucerne at the Buick dealership...
Figure 3: The UML diagram for the car ordering application.

You can use the Factory Method design pattern to create a software framework. The car ordering application (using the Factory Method) is a framework with a pre-written orderCar() method. To this basic framework, you can add concrete classes for new makes and models of cars.

Listing 1 though 6

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 38
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Microsoft's Novell Investment Tops $340M
Fedora 10 Takes Shape
IBM Gives a Mobile Voice to Developers
Inadequate Tools Send Software Down the Drain
USB 3.0 One Step Closer to Reality
Would-Be Linux Contributors May Get a Leg Up
SAP, Oracle Holding Out on Ubuntu?
GIPS Technology to Voice-Enable iPhone Apps
Citrix CTO Eyes the Future of Virtualization
The Pitfalls of Open Source Litigation

DevXtra Editors' Blog: Executives Avoiding Cloud Computing in Droves
Q&A with James Reinders on the Intel Parallel Studio Beta Program
The Pros and Cons of Outsourcing Enterprise Emails
Hosting Options: Shared or Dedicated Server
Movin' On Up: How to Hop to a New Host
Simplifying Composite Applications with Service Component Architecture
The Guide to E-Mail Archiving and Management
Making XQuery Control Structures Work for You
Overview: C++ Gets an Overhaul
Sharpening Your Axis with Visual Basic 9

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers