From Design patterns for dummies:
There you go — you’ve got a factory class
What I have understood from factory pattern is that it helps us to avoid constant code modification whenever a new object needs to be created. But the function createConnection
won't have to be modified it to create and add another object? So how is this helpful?
What's the point that I am missing?
The factory pattern can be used to limit the number of code changes you have to do. Using your code as an example, imagine you have lots of functions which use database connections
void ExampleMethod() {
var con = new MySqlConnection();
// do something with con
}
And now you want to use Oracle instead of MySQL so you have to change every single line that says new MySqlConnection
into new OracleConnection
.
A factory can solve this problem
void ExampleMethodUsingFactories() {
var con = factoryInstance.createConnection();
}
where factoryInstance
is instantiated only once with factoryInstance = new FirstFactory("MySql")
. Changing the entire program to use Oracle becomes trivial now. You only have to replace "MySQL" by "Oracle". You don't have to change the methods that actually use the database connection.
Of course adding a new database engine still means you have to change the factory code, but that's only in one class.