The FactoryMethod Pattern
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
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); } } }
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; } }