|
|||
Written by Algis Rudys and Stephen HueyWhat do you do when you'd rather let a subclass decide which class of object to instantiate? Use the Factory Pattern! The Factory Pattern, called Abstract Factory in the Design Patterns book (see page 87) is used to facilitate class instantiation by some client of the class being instantiated. In the Abstract Factory pattern, a special class, called a factory, is created whose sole purpose is to instantiate instances of a class. There are two reasons one might want to do this. The first is that the factory is an object instance, which means it can be passed as an argument to a method. This allows an extra level of indirection in creating objects and passing them as parameters. The second reason has to do with the pattern's name, Abstract Factory. It gets this name because the factory class itself is generally an abstract class. The concrete subclass of the abstract factory actually decides what to instantiate. For instance, if you want to instantiate a concrete subclass of abstract class The following image from Design Patterns illustrates this.
The Factory Method pattern (see page 107 of Design Patterns) refers to a similar design pattern, wherein instead of being in a separate class, the factory functionality is within a method of the client class itself. The client class can be subclassed to determine which concrete subclass of the product is actually instantiated. Out in the real world, the lines probably blur when developers implement either or both of them. For more info, see http://www.research.umbc.edu/~tarr/cs491/lectures/Factory-2pp.pdf Here's the Maze Game code: http://www.cecs.csulb.edu/~tayek/morePatterns/#Factory Images and the Maze example from this page and the two links come from the Design Patterns book.
|