Home > Articles > Software Development & Management

This chapter is from the book

This chapter is from the book

Introduce Polymorphic Creation with Factory Method

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.

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.
  2. 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.

  3. 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.
  4. → Compile and test.

  5. 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.
  6. The participant name for the superclass of the sibling subclasses is Factory Method: Creator [DP].

    → Compile and test.

  7. 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.

  8. Repeat steps 1–4 if you have additional similar methods in the sibling subclasses that could benefit from calling the previously created factory method.
  9. 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.
  10. → 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:
  2. 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.

  3. Now I repeat step 1 for all other sibling subclasses, which in this case is just XMLBuilderTest:
  4. 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.

  5. 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:
  6. public class AbstractBuilderTest extends TestCase {
    }
       
    public class XMLBuilderTest extends AbstractBuilderTest...
       
    public class DOMBuilderTest extends AbstractBuilderTest...
  7. 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:
  8. 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.

  9. Since there are additional similar methods between XMLBuilderTest and DOMBuilderTest, I repeat steps 1–4 for each similar method.
  10. 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020