At times, an application object may only know that it needs to access a class from within the class hierarchy, but does not know exactly which class from among the set of subclasses of the parent class is to be selected. The choice of an appropriate class may depend on factors such as:
- The state of the running application
- Application configuration settings
- Expansion of requirements or enhancements
In such cases, the Factory Method pattern recommends encapsulating the functionality required, to select and instantiate an appropriate class, inside a designated method referred to as a factory method. Thus, a factory method can be defined as a method in a class that:
- Selects an appropriate class from a class hierarchy based on the application context and other influencing factors
- Instantiates the selected class and returns it as an instance of the parent class type
One of the simplest ways of designing a factory method is to create an abstract class or an interface that just declares the factory method. Different subclasses (or implementer classes in the case of an interface) can be designed to implement the factory method. Another strategy is to create a concrete creator class with default implementation for the factory method in it. Different subclasses of this concrete class can override the factory method to implement specialized class selection criteria.
Example
Consider an application object that intends to use the services provided by the Logger implementers. Suppose that the overall application message logging configuration can be specified using the logger.properties property file.
Depending on the value of the FileLogging property, an appropriate Logger implementer needs to be used to log messages. For example, if the FileLogging property is set to ON, messages are to be logged to a file and hence a FileLogger object can be used to log messages. Similarly, if the FileLogging property is set to OFF, messages are to be displayed on the console and hence a ConsoleLogger object can be used.
To log messages, an application object needs to:
- Identify an appropriate Logger implementer by reading the FileLogging property value from the logger.properties file
- Instantiate the Logger implementer and invoke the log method by passing the message text to be logged as an argument
No comments:
Post a Comment