JMU
The FactoryMethod Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Overview
A Model
images/factorymethod.gif
A Generic Example
images/factorymethod_pooled.gif
A Specific Example

The Class to be Constructed

javaexamples/factorymethod/DirectoryListing.java
import java.io.*;
import java.util.*;

/**
 * An encapsulation of the contents of a directory
 *
 * This class is part of an example that illustrates the use of
 * the FactoryMethod pattern
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class DirectoryListing
{
    private File        dir;
    private File[]      files;
    private long        lastTimeCheck;


    /**
     * Explicit Value Constructor
     *
     * @param path    The path to the directory
     */
    DirectoryListing(String path) // package visibility
    {
       dir = new File(path);

       lastTimeCheck = 0;
       update();
    }


    /**
     * Get the contents of this DirectoryListing
     *
     * @return   The array of File objects (sorted by name)
     */
    public File[] getContents()
    {
       update();
       return files;
    }


    /**
     * Update this DirectoryListing if necessary
     */
    private void update()
    {
       long        lastModified;

       lastModified = dir.lastModified();
       if (lastTimeCheck != lastModified) 
       {
          lastTimeCheck = lastModified;
          files         = dir.listFiles();
          Arrays.sort(files);
       }
    }
}
        
An Example (cont.)

The Factory

javaexamples/factorymethod/DirectoryListingFactory.java
import java.util.*;

/**
 * A factory that creates DirectoryListing objects
 *
 * This class is part of an example that illustrates the use of
 * the FactoryMethod pattern.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class DirectoryListingFactory
{
    private Map<String,DirectoryListing>   pool;


    /**
     * Default Constructor
     */
    public DirectoryListingFactory()
    {
       pool = new HashMap<String,DirectoryListing>();
    }


    /**
     * Create a DirectoryListing object
     *
     * Because DirectoryListing objects are expensive to create,
     * this method may return an existing DirectoryListing object
     * if one exists
     *
     * @param path    The path to the directory
     * @return        The DirectoryListing
     */
    public DirectoryListing createDirectoryListing(String path)
    {
       DirectoryListing       dl;

       dl = pool.get(path);
       if (dl == null) 
       {
          dl = new DirectoryListing(path);
          pool.put(path, dl);
       }
        
       return dl;
    }

}