Im currently implementing an abstract factory pattern for database connectivity, I need to separate business logic, and have code that does not need to be rewritten for each new database-type that needs to connect to my application, So at this point I have these classes
Interface Connection{}
MySql implements Connection{}
PostgreSql implements Connection{}
So the problem here is that each class that implements the interface Connection has to rewrite the methods in the interface, I would need a class where there are general methods like setStatement, executeQuery, etc, but then som methods would need to be overwritten like connect method which will differ depending on the databasetype,
My first thought is to have an extra class between the interface Connection and the subclasses, where the methods are kept and used if not overridden, but this solution does not feel like the right way (correct me if im wrong)
Interface ConnectionInterface{}
class Connection{}
MySql extends Connection{}
PostgreSql extends Connection{}
Thanks
I don't see why not consider the State design pattern over inheritance. Here is an additional very good post - why?
By doing so
can alter an
Connection
behavior when its type changes. Also will appear already changed accordingly. The state pattern also allows you to keep attributes of a former state even when the state changes afterwards.Pseudo code of the implementation:
Nothing wrong with that. But I would do it like this:
With Java 8 you could also use default Methods in the interface and leave out the abstract class.
A completely alternative approach would be a class
DefaultConnectionOperations
that provides the methods. Then you could have an object of this class, which is injected into each Connection-Implementation. But it is arguable, if dependency injection is necessary in your case.