lundi 6 janvier 2020

How Factory Method pattern make code maintainable in this case

I'm new to design patterns, I was reading a book says: In an application, you may have different database users. For example, one user may use Oracle, and the other may use SQL Server. Whenever you need to insert data into your database, you need to create either a SqlConnection or an OracleConnection and only then can you proceed. If you put the code into if-else (or switch) statements, you need to repeat a lot of code, which isn’t easily maintainable. This is because whenever you need to support a new type of connection, you need to reopen your code and make those modifications. This type of problem can be resolved using the Factory Method pattern.

I'm a little bit confused here, if you need to use a new type of connection, don't you just add a new class file of that connection class (e.g.

NEWGenerationConnection), then just use NewGenerationConnection connection = new NewGenerationConnection(connectionString); connection.open(); .... how does if-else get involved here? and why you need to modify the base code file? can someone write some pseudo code for me so that I can understand the problem better?

Aucun commentaire:

Enregistrer un commentaire