代表或代理人或其他人

时间:2016-10-29 07:30:44

标签: java design-patterns

我想通过其类型处理不同的结果。这是我的代码

public interface Handler {
  void handle(Result result)
}

public class HandlerA implement Handler {
   public handle(Result result) {
      //do something
   }
}
public class HandlerB implement Handler {
   public handle(Result result) {
      //do something
   }
}
//....
public class HandlerImpl implement Handler {
  //..
    Handler A = new HandlerA();
    Handler B = new HandlerB();
  //..
  public void handle(Result result) {
    switch (result.getType()){
      case A:
       A.handle(result);
       break;
      case B:
       B.handle(result);
       break;
       //....
    }
  }
}

服务

public class Service{
   Handler handler = new HandlerImpl();
   public process() {
     //..
     Result result = .....
     handler.handle(result);
     //...
   }
}

但我觉得有关HandlerImpl的看法,我认为它可能不应该实现Handle。我已经阅读了一些关于Proxy / Delefate设计模式的博客,我没有得到更好的工具。任何人都有一些关于如何实现这个功能的更好的建议。非常感谢

1 个答案:

答案 0 :(得分:0)

Factory怎么样?

工厂将分开布线'从执行开始,允许可扩展性。

public class YourClass {
    // ...
    HandlerFactory handlerFactory; // create or get injected

    void yourMethod() {
        Result result = ....
        Handler h = handlerFactory.get(result);
        h.handle(result);
    }

}

public class HandlerFactory {

    private static HandlerFactory INSTANCE;

    private final Map<ResultType, Handler> resultHandlers = new HashMap<>();

    private HandlerFactory() {
        // not externaly instantiable
    }

    /** register a handler for a result type */
    public void register(ResultType type, Handler handler) {
        resultHandlers.put(type, handler);
    }

    /** retrieves a handler for a result type */
    public Handler get(Result result) {
        Hanlder result = resultHandlers.get(result.getType);
        // optional: throw exception if type not mapped
        return result;
    }

    /** provides an initialized factory instance. */
    public synchronized static HandlerFactory getInstance() {
        if (INSTANCE == null) {
            INSTANCE = createFactoryWithDefaultMappings();
        }
        return INSTANCE;
    }

    private static HandlerFactory createFactoryWithDefaultMappings() {
        HandlerFactory factory = new HandlerFactory();
        // register default handlers
        factory.register(ResultType.A, new HandlerA());
        factory.register(ResultType.B, new HandlerB());
        return factory;
    }

}