我將執行數據映射器模式以將數據存儲在不同的存儲/數據庫中。實施不同存儲策略的模式
實現此概念的最佳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類?
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 */
}
只是一個警告 - 在您的問題中使用「最好」可能會吸引「主要基於意見」的密切投票 – awksp
@ user3580294感謝您的注意:) – zavg
對我來說似乎很好。我會把它稱爲UserDAO而不是UserMapper,儘管 –