The factory method pattern for instantiation
Now, we should take care of the instantiation of the right object based on the parameter received (often retrieved from a configuration file ) to identify the strategy.
Note
We will use the GoF factory method pattern to instantiate the LogStrategy
object. By checking the loggertype
parameter, the appropriate concrete class will be instantiated.
public static LogStrategy CreateLogger(string loggertype) { if (loggertype == "DB") return new DbLogStrategy(); else if (loggertype == "FILE") return new FileLogStrategy(); else if (loggertype == "NET") return new NetLogStrategy(); else return new NullLogStrategy(); }
The application developer can also control the logging strategy through a configuration entry. The process of instantiating the LogStrategy
class is given as follows:
string loggertype=read_from_config("loggertype...