一个包含连接方法以及选择、插入、更新、删除方法的类是否违反了单一责任原则?
class Database:
def create_connection(self, url):
...
def select(self):
...
def insert(self):
...
def update(self):
...
def delete(self):
...
由于您上面的类至少有两项职责,即创建数据库连接和对实体执行CRUD操作,因此我认为这违反了SOLID的单一责任原则。
您可以创建一个单独的类来处理数据库连接,并将其注册为执行CRUD操作的数据库类的依赖项(通过接口(。以下是它的样子:
//Pseudo code
interface IDatabaseConnection:
def create_connection(url):
...
class SqlDatabaseConnection implements IDatabaseConnection:
def create_connection(url):
...
class DatabaseService:
private IDatabaseConnection _dbConnection;
constructor(IDatabaseConnection dbConnection):
self._dbConnection = dbConnection
def select(self):
//use the dbConnection here to create a connection
//perform your select operation
...
def insert(self):
//use the dbConnection here to create a connection
//perform your insert operation
...
def update(self):
...
def delete(self):
...
以下是我们将如何使用它。
DatabaseService service = new DatabaseService(
new SqlDatabaseConnection(dbConnectionString)
);
...
service.insert(entity);
...
这也允许您对数据库连接使用其他SOLID原则。
提示:如果我有很多选择操作,我可能会为CRUD操作创建单独的类,如下所示:
class SelectEntityDatabaseService implements ISelectEntityDatabaseService {...}
class CreateEntityDatabaseService implements ICreateEntityDatabaseService {...}
class UpdateEntityDatabaseService implements IUpdateEntityDatabaseService {...}
...