2016-10-29 12 views
0

その種類によって異なる結果を扱いたいと思っています。そして、ここに私のコード代理人または代理人またはその他

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のデザインパターンについていくつかのブログを読んだが、私はいくつかの優れた実装を得ていなかった。誰でもこのファンクションをどのように実施するかについて、より良い提案があります。多くのありがとう

+0

ハンドラが実装されない理由はわかりません。実際のコンパイルコードを見ずにアドバイスをするのは難しいです。結果は何ですか? getType()は実際に何を返しますか? –

答えて

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; 
    } 

}