Abstract factory pattern interface implementation

2019-08-29 14:48发布

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

2条回答
等我变得足够好
2楼-- · 2019-08-29 14:56

I don't see why not consider the State design pattern over inheritance. Here is an additional very good post - why?

By doing so

each new database-type

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:

class Connection{
private State _state;
}

abstract  class State{
protected Connection connection;
}

class MySqlState extends State{}
class PostgreSqlState extends State {}
查看更多
可以哭但决不认输i
3楼-- · 2019-08-29 14:59

Nothing wrong with that. But I would do it like this:

interface Connection{}
abstract class AbstractConnection implements Connection {}
final class MySql extends AbstractConnection{}
final class PostgreSql extends AbstractConnection{}

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.

查看更多
登录 后发表回答