首页 > 解决方案 > 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?

标签: javadesign-patterns

解决方案


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


推荐阅读