如何重构此方法?(Spring Java8)



我试图重构下面的Java类。我有一种方法可以根据其属于哪个实例保存POJO(实体(。

下面的代码仅显示3个服务,但总共有13个服务。每个服务都在调用单独的 *RepositoryImpl。例如,ActivitesService是一个接口,而ActivitesService.Create(活动(将调用该接口的实现。

@Autowired
private ActiviteService       activiteService;
@Autowired
private AdresseMsSanteService    adresseMsSanteService;
@Autowired
private AttributionParticuliereService     attributionParticuliereService;

private boolean sauvegarder(Object object, Long idIdPlay, String game,
    Integer gameIndex) {

    boolean isSaved = false;
    if (idIdPlay == null) {
        throw new IllegalArgumentException("IdPlay id is null");
    }
    if (object instanceof Activite) {
        Activite activite = (Activite) object;
        activite.setIdIdPlay(idIdPlay);
        if (this.isGameOn(activite, game, gameIndex)) {
            activiteService.create(activite);
            isSaved = true;
        }
    } else if (object instanceof AdresseMsSante) {
        AdresseMsSante adresseMsSante = (AdresseMsSante) object;
        adresseMsSante.setIdIdPlay(idIdPlay);
        if (this.isGameOn(adresseMsSante, game, gameIndex)) {
            adresseMsSanteService.create(adresseMsSante);
            isSaved = true;
        }
    } else if (object instanceof AttributionParticuliere) {
        AttributionParticuliere attributionParticuliere = (AttributionParticuliere) object;
        attributionParticuliere.setIdIdPlay(idIdPlay);
        if (this.isGameOn(attributionParticuliere, game, gameIndex)) {
            attributionParticuliereService.create(attributionParticuliere);
            isSaved = true;
        }
    } else if 

首先,我将创建一个代表您的游戏实体的接口。例如:

public interface GameEntity {
    void setIdIdPlay(Long idIdPlay);
}

之后,您创建了实现游戏界面接口的类:

@Entity
@Table
public class AdresseMsSante implements GameEntity {
    @Id
    Long idIdPlay;
    public void setIdIdPlay(Long idIdPlay) {
        this.idIdPlay = idIdPlay;
    }
}

@Entity
@Table
public class Activite implements GameEntity {
    @Id
    Long idIdPlay;
    public void setIdIdPlay(Long idIdPlay) {
        this.idIdPlay = idIdPlay;
    }
}

然后,创建您的通用存储库,以节省每个游戏实体。

@Repository
public class Repo {
    @Autowired
    EntityManager entityManager;
    @Transactional
    public void save(GameEntity obj) {
        entityManager.merge(obj);
    }
}

最后,您的方法就是这样:

 @Autowired
    Repo repo;
 private boolean sauvegarder(Object object, Long idIdPlay, String game,
                                Integer gameIndex) {
        boolean isSaved = false;
        if (idIdPlay == null) {
            throw new IllegalArgumentException("IdPlay id is null");
        }
        GameEntity gameEntity = (GameEntity) object;
        gameEntity.setIdIdPlay(idIdPlay);
        if(this.isGameOn(gameEntity, game, gameIndex)) {
            repo.save(gameEntity);
            isSaved = true;
        }
        return isSaved;
    }

    boolean isGameOn(GameEntity gameEntity,  String game, Integer gameIndex) {
        // do something
        return true;
    }