什么是以下代码的正确设计模式?

时间:2017-09-23 09:01:53

标签: java oop design-patterns

我有以下课程:

class ServiceA{
    User getUser(){} // API call to userServiceA.com
    Profile getProfile(){} // API call to profileServiceA.com
}

class ServiceB{
    User getUser(){} // API call to userServiceB.com
    Profile getProfile(){} // API call to profileServiceB.com
}

class GroupService(){
    ServiceA serviceA;
    ServiceB serviceB;
    constructor(){
        this.serviceA = new ServiceA();
        this.serviceB = new ServiceB();
    }

    getUser(String type){
        if(type.equals("A")){
            serviceA.getUser();
        }else if(type.equals("B")){
            serviceB.getUser();
        }
    }
}

class Controller(){
    get(RC routingContext){
        String type = routingContext.getParam("type");
        GroupService groupService = new GroupService();
        groupService.getUser(type);
    }
}

在此项目中,ServiceC,D,E...将继续添加,这会将GroupService类变为混乱。

对于这种特殊情况,我可以应用哪种正确的设计模式? Factory模式是一种解决方案,但if elseMap仍然存在。

更新:使用策略模式

public interface ServiceAZ {
  User getUser();
  Profile getProfile();
}

class ServiceA implements ServiceAZ{

  @Override
  public User getUser() {
            return // API call to userServiceA.com
  }

  @Override
  public Profile getProfile() {
      return // API call to profileServiceA.com
  }
}

class ServiceB implements ServiceAZ{

  @Override
  public User getUser() {
            return // API call to userServiceB.com
  }

  @Override
  public Profile getProfile() {
      return // API call to profileServiceB.com
  }
}

class GroupService(){
    private ServiceAZ service;
    GroupService(ServiceAZ s){
        this.service = s;
    }
    User getUser(){
        service.getUser();
    }
}

class Controller(){
    get(routingContext){
        String type = routingContext.getParam("type");
        ServiceAZ service; 
        if(type.equals("A")){
            service = new ServiceA();
        }
        if(type.equals("B")){
            service = new ServiceB();
        }
        GroupService groupService = new GroupService(service);
        groupService.getUser(type);
    }
}

这看起来好多了,但现在在控制器中,if else是一个问题

0 个答案:

没有答案