Introduce Polymorphic Creation with Factory Method

Prev don't be afraid of buying books Next

Introduce Polymorphic Creation with Factory Method

Classes in a hierarchy implement a method similarly, except for an object creation step.



Make a single superclass version of the method that calls a Factory Method to handle the instantiation.





Motivation

To form a Creation Method (see Replace Constructors with Creation Methods, 57), a class must implement a static or nonstatic method that instantiates and returns an object. On the other hand, if you wish to form a Factory Method [DP], you need the following:

  • A type (defined by an interface, abstract class, or class) to identify the set of classes that Factory Method implementors may instantiate and return

  • The set of classes that implement that type

  • Several classes that implement the Factory Method, making local decisions about which of the set of classes to instantiate, initialize, and return

While that may sound like a tall order, Factory Methods are most common in object-oriented programs because they provide a way to make object creation polymorphic.

In practice, Factory Methods are usually implemented within a class hierarchy, though they may be implemented by classes that simply share a common interface. It is common for an abstract class to either declare a Factory Method and force subclasses to override it or to provide a default Factory Method implementation and let subclasses inherit or override that implementation.

Factory Methods are often designed into framework classes to make it easy for programmers to extend a framework's functionality. Such extensions are commonly implemented by subclassing a framework class and overriding a Factory Method to return a specific object.

Because the signature of a Factory Method must be the same for all implementers of the Factory Method, you may be forced to pass unnecessary parameters to some Factory Method implementers. For example, if one subclass requires an int and a double to create an object, while another subclass requires only an int to create an object, a Factory Method implemented by both subclasses will need to accept both an int and a double. Since the double will be unnecessary for one subclass, looking at the code may be a bit confusing.

Factory Methods are often called by Template Methods [DP]. The collaboration of these two patterns frequently evolves into a class hierarchy as a result of refactoring to rid the hierarchy of duplicate code. For example, imagine that you find a method either in a superclass and overridden by a subclass or in several subclasses, and this method is implemented nearly identically in these places except for an object creation step. You see how you could replace all versions of this method with a single superclass Template Method, provided that the Template Method can issue one object creation call without knowing the class of object that the superclass and/or subclasses will instantiate, initialize, and return. No pattern is better suited to that task than Factory Method.

Is using a Factory Method simpler than calling new or calling a Creation Method? The pattern certainly isn't simpler to implement. However, the resulting code that uses a Factory Method tends to be simpler than code that duplicates a method in several classes just to perform custom object creation.

Benefits and Liabilities

+

Reduces duplication resulting from a custom object creation step.

+

Effectively communicates where creation occurs and how it may be overridden.

+

Enforces what type a class must implement to be used by a Factory Method.

May require you to pass unnecessary parameters to some Factory Method implementers.







Mechanics

This refactoring is most commonly used in the following situations:

  • When sibling subclasses implement a method similarly, except for an object creation step

  • When a superclass and subclass implement a method similarly, except for an object creation step

The mechanics presented in this subsection handle the sibling subclasses scenario and can easily be adapted for the superclass and subclass scenario. For the purposes of these mechanics, a method that is implemented similarly in a hierarchy, except for an object creation step, will be called a similar method.

1. In a subclass that contains a similar method, modify the method so the custom object creation occurs in what these steps will call an instantiation method. You'll usually do this by applying Extract Method [F] on the creation code or by refactoring the creation code to call a previously extracted instantiation method.

Use a generic name for the instantiation method (e.g., createBuilder, newProduct) because the same method name will need to be used in the sibling subclass's similar methods. Make the return type for the instantiation method be the type that is common for the custom instantiation logic in the sibling subclass's similar methods.

  • Compile and test.

2. Repeat step 1 for the similar method in the sibling subclasses. This should yield one instantiation method for each of the sibling's subclasses, and the instantiation method's signature should be the same in every sibling subclass.

  • Compile and test.

3. Next, modify the superclass of the sibling subclasses. If you can't modify that class or would rather not do so, apply Extract Superclass [F] to produce a superclass that inherits from the superclass of the sibling subclasses and makes the sibling subclasses inherit from the new superclass.

The participant name for the superclass of the sibling subclasses is Factory Method: Creator [DP].

  • Compile and test.

4. Apply Form Template Method [F] on the similar method. This will involve applying Pull Up Method [F]. When you apply that refactoring, be sure to implement the following advice, which comes from a note in the mechanics for Pull Up Method [F]:

If you are in a strongly typed language and the [method you want to pull up] calls another method that is present on both subclasses but not the superclass, declare an abstract method on the superclass. [F, 323]

One such abstract method you'll declare on the superclass will be for your instantiation method. Having declared that abstract method, you will have implemented a factory method. Each of the sibling subclasses is now a Factory Method: ConcreteCreator [DP].

  • Compile and test.

5. Repeat steps 1–4 if you have additional similar methods in the sibling subclasses that could benefit from calling the previously created factory method.

6. If the factory method in a majority of ConcreteCreators contains the same instantiation code, move that code to the superclass by transforming the factory method declaration in the superclass into a concrete factory method that performs the default ("majority case") instantiation behavior.

  • Compile and test.

Example

In one of my projects, I had used test-driven development to produce an XMLBuilder—a Builder [DP] that allowed clients to easily produce XML. Then I found that I needed to create a DOMBuilder, a class that would behave like the XMLBuilder, only it would internally produce XML by creating a Document Object Model (DOM) and give clients access to that DOM.

To produce the DOMBuilder, I used the same tests I'd already written to produce the XMLBuilder. I needed to make only one modification to each test: instantiation of a DOMBuilder instead of an XMLBuilder:

 public class DOMBuilderTest extends TestCase...   private OutputBuilder builder;   public void testAddAboveRoot() {    String invalidResult =    "<orders>" +      "<order>" +      "</order>" +    "</orders>" +    "<customer>" +    "</customer>";    builder =  new DOMBuilder("orders");  // used to be new XMLBuilder("orders")    builder.addBelow("order");    try {      builder.addAbove("customer");      fail("expecting java.lang.RuntimeException");    } catch (RuntimeException ignored) {}   } 

A key design goal for DOMBuilder was to make it and XMLBuilder share the same type: OutputBuilder, as shown in the following diagram.

After writing the DOMBuilder-, I had nine test methods that were nearly identical on the XMLBuilderTest and DOMBuilderTest. In addition, DOMBuilderTest had its own unique tests, which tested access to and contents of a DOM. I wasn't happy with all the test-code duplication, because if I made a change to an XMLBuilderTest, I needed to make the same change to the corresponding DOMBuilderTest. I knew it was time to refactor to the Factory Method. Here's how I went about doing that work.

1. The similar method I first identify is the test method, testAddAboveRoot(). I exTRact its instantiation logic into an instantiation method like so:

 public class DOMBuilderTest extends TestCase...    protected OutputBuilder createBuilder(String rootName) {      return new DOMBuilder(rootName);    }   public void testAddAboveRoot() {     String invalidResult =     "<orders>" +       "<order>" +       "</order>" +     "</orders>" +     "<customer>" +     "</customer>";     builder =  createBuilder("orders");     builder.addBelow("order");     try {       builder.addAbove("customer");       fail("expecting java.lang.RuntimeException");     } catch (RuntimeException ignored) {}   } 

Notice that the return type for the new createBuilder(…) method is an OutputBuilder. I use that return type because the sibling subclass, XMLBuilderTest, will need to define its own createBuilder(…) method (in step 2) and I want the instantiation method's signature to be the same for both classes.

I compile and run my tests to ensure that everything's still working.

2. Now I repeat step 1 for all other sibling subclasses, which in this case is just XMLBuilderTest:

 public class XMLBuilderTest extends TestCase...    private OutputBuilder createBuilder(String rootName) {      return new XMLBuilder(rootName);    }   public void testAddAboveRoot() {     String invalidResult =     "<orders>" +       "<order>" +       "</order>" +     "</orders>" +     "<customer>" +     "</customer>";     builder =  createBuilder("orders");     builder.addBelow("order");     try {       builder.addAbove("customer");       fail("expecting java.lang.RuntimeException");     } catch (RuntimeException ignored) {}   } 

I compile and test to make sure the tests still work.

3. I'm now about to modify the superclass of my tests. But that superclass is TestCase, which is part of the JUnit framework. I don't want to modify that superclass, so I apply Extract Superclass [F] to produce AbstractBuilderTest, a new superclass for my test classes:

  public class AbstractBuilderTest extends TestCase {  } public class XMLBuilderTest  extends AbstractBuilderTest... public class DOMBuilderTest  extends AbstractBuilderTest... 

4. I can now apply Form Template Method (205). Because the similar method is now identical in XMLBuilderTest and DOMBuilderTest, the Form Template Method mechanics I must follow instruct me to use Pull Up Method [F] on testAddAboveRoot(). Those mechanics first lead me to apply Pull Up Field [F] on the builder field:

 public class AbstractBuilderTest extends TestCase {   protected OutputBuilder builder; } public class XMLBuilderTest extends AbstractBuilderTest...     private OutputBuilder builder; public class DOMBuilderTest extends AbstractBuilderTest...     private OutputBuilder builder; 

Continuing with the Pull Up Method [F] mechanics for testAddAboveRoot(), I now find that I must declare an abstract method on the superclass for any method that is called by testAddAboveRoot() and present in the XMLBuilderTest and DOMBuilderTest. The method, createBuilder(…), is such a method, so I pull up an abstract method declaration of it:

 public  abstract class AbstractBuilderTest extends TestCase {   protected OutputBuilder builder;    protected abstract OutputBuilder createBuilder(String rootName); } 

I can now proceed with pulling up testAddAboveRoot() to AbstractBuilderTest:

 public abstract class AbstractBuilderTest extends TestCase...    public void testAddAboveRoot() {      String invalidResult =      "<orders>" +        "<order>" +        "</order>" +      "</orders>" +      "<customer>" +      "</customer>";      builder = createBuilder("orders");      builder.addBelow("order");      try {        builder.addAbove("customer");        fail("expecting java.lang.RuntimeException");      } catch (RuntimeException ignored) {}    } 

That step removed testAddAboveRoot() from XMLBuilderTest and DOMBuilderTest. The createBuilder(…) method, which is now declared in AbstractBuilderTest and implemented in XMLBuilderTest and DOMBuilderTest, now implements the Factory Method [DP] pattern.

As always, I compile and test my tests to make sure that they still work.

5. Since there are additional similar methods between XMLBuilderTest and DOMBuilderTest, I repeat steps 1–4 for each similar method.

6. At this point I consider creating a default implementation of createBuilder(…) in AbstractBuilderTest. I would only do this if it would help reduce duplication in the multiple subclass implementations of createBuilder(…). In this case, I don't have such a need because XMLBuilderTest and DOMBuilderTest each instantiate their own kind of OutputBuilder. So that brings me to the end of the refactoring.

Amazon


Refactoring to Patterns (The Addison-Wesley Signature Series)
Refactoring to Patterns
ISBN: 0321213351
EAN: 2147483647
Year: 2003
Pages: 103

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net