In this example below based on the value of the paramater datasource we would need to decide which implementation of IDatasource to use. The problem with a code like this is that it does not adhere to the "closed for modification" design principle. If you add a new implementation of IDataSource called DataFromFile, then you will have to modify the code in the Main() and add a new else statement. Ideally, when you add a new implementation or switch implementation, you shouldn't have to modify code.
To switch from DataFromSQL to DataFromXML, all I should have to do, should be to change a config setting. Factory pattern helps us achieve that.
Simple Factory Pattern
In this pattern we do not need to update the code if we want to switch implementations. All we do is make a change in the config file. These are the key things we need to do to make this happen.
- Save the name of Implementation of IDatasource we want to use in the config file.
- Load into a Dictionary, all the implementations of IDataSource that we have in the current assembly.
- Get the name of implementation from the config file. Pass that class name into a method. That method looks up the dictionary dataSources for a type that matches the class name (type name) we just passed in. Then it creates an instance of that for us.
Its called factory pattern because, you pass the name of a class to a factory and it returns an instance of that class for you.