【发布时间】:2014-06-16 08:13:56
【问题描述】:
我将实现 Data Mapper 模式以将数据存储在不同的存储/数据库中。
实现这个概念的最佳 OOP 模式是什么?
比如我有User模型类
public class User
{
private int id;
private String name;
private String surname;
/* getters, setters and model-level business logic */
}
和适当的数据映射器类
public class UserMapper
{
public User findById(int id)
{
// perform query to MySQL, Redis or another DB
}
/* other methods */
}
通过创建多个存储策略类然后将它们注入 DataMapper 类来使用 Strategy 模式是不是一个好主意?
public class UserMySQLStorageStrategy extends UserStorageStrategy
{
public User findById(int id)
{
// perform query to MySQL
}
}
public class UserRedisStorageStrategy extends UserStorageStrategy
{
public User findById(int id)
{
// perform query to Redis
}
}
public class UserMapper
{
protected UserStorageStrategy _storageStrategy;
public UserMapper(UserStorageStrategy storageStrategy)
{
this._storageStrategy = storageStrategy;
}
public User findById(int id)
{
return this._storageStrategy.findById(id);
}
/* other methods */
}
【问题讨论】:
-
只是一个警告 - 在您的问题中使用“最佳”可能会吸引“主要基于意见”的密切投票
-
@user3580294 感谢您的注意 :)
-
对我来说似乎很好。我会称它为 UserDAO 而不是 UserMapper
标签: java design-patterns