java - Consistency of return type
问题描述
We have a Gateway
class that is injected with a persistence medium on initialization.
The business classes will invoke the gateway to persist or request data.
Class Gateway {
Repository rep;(injected on initialization)
public PersistTypeEnum persistEmployee(Employee){ ... rep.persist......}
public PersistTypeEnum persistEmployer(Employer){ ... rep.persist......}
public PersistTypeEnum persistEmployeeForEmployer(EployerEmployee){ ... rep.persist......}
getEmployee(){ ....rep.getmployee....}
......................................
}
We need to enforce that every persist call via Gateway
returns PersistTypeEnum
.
Any recommended practice/pattern for enforcing or achieving this?
解决方案
Implement Strategy Pattern. For example instead of adding new persistEmployee
methods extract this logic outside Gateway
class to some processor classes with common interface like
public interface Persistor<T extends Persistable> { // Persistable would be common interface for Employee, Employer, ...
PersistTypeEnum persist(T Item, Class<T> itemClass);
}
and inside your Gateway store such Persistors
inside a map grouped by Class
. Then write dispatcher method to call such implementations
Map<Class<? extends Persistable>, Persistor> persistors = initializePersistors(); // even better some dependency injection here
...
public <T extends Persistable> PersistTypeEnum persist(T Item, Class<T> itemClass) {
return persistors.get(itemClass).persist(item); // handle 'no such key' exception
}
This is of course suggestion and there are probably better ways how to implement this, but this approach, I believe, will resolve your issue
推荐阅读
- java - 在消费者表达式中返回方法值
- ios - 如何在 App Delegate 的“performFetchWithCompletionHandler”函数中从 Alamofire 获取数据?
- python - 为什么此颜色条标签代码适用于 Matplotlib 2.2.3 但不适用于 Matplotlib 3.0.1?
- node.js - Cloud9:找不到开放端口
- javascript - 数组到元素 javascript
- ruby-on-rails - Rails如何在参数中封装2个var?
- java - 使用非静态内部类在 MainActivity 中接收广播
- python-3.x - 在 Linux 命令中使用命令“import os”失败?
- c# - 广义 DocumentDB / CosmosDB 分区策略
- javascript - jquery加载多行