使用java泛型的责任链处理程序 [英] chain-of-responsibility handler with java generics

查看:402
本文介绍了使用java泛型的责任链处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java中的责任链设计模式。链作为一个整体代表对某些类型的对象的请求。链中的每个处理程序负责处理所请求的1种单位。
所有请求的处理方式基本相同,所以我尝试使用Handler类通用。
所以在Handle类中我需要一个像这样的方法(处理本身是简化的,因为它只会模糊我的问题):

I'm using the Chain of Responsibility design-pattern in Java. The chain as a whole represents a request for objects of certain types. Each "Handler" in the chain is responsible to handle the requested units of 1 type. All requests are handled in essentially the same way so I tried making the "Handler"-class generic. So in the Handle-class I need a method like this (the handling itself is simplified because it would only obfuscate my problem):

public class Handler<T>{
   int required;
   Handler<?> next;

   public void handle(Object O){
      if(o instanceof T){
         required --;
      }else{
         next.handle(o);
      }
   }
}

问题在于这是不可能的。因为类型T在运行时没有明确存储(或者这是我在互联网研究中所理解的)。所以我的问题是:什么是最好的选择?

The problem is that an instanceof like this is impossible. Because the type T isn't explicitly stored during run time (or that's what I understood during my research on the internet). So my question is: what is the best alternative?

推荐答案

使用构造函数参数来定义类,使用泛型实现处理程序处理程序支持:

Implement handlers using generics by using a constructor parameter to define the class the handler supports:

public class Handler<T> {
    private int required;
    private Handler<?> next;
    private Class<? extends T> c;

    public Handler(Class<? extends T> c) {
        this.c = c;
    }

    public void handle(Object o) {
        if (c.isInstance(o)) {
            required--;
        } else {
            next.handle(o);
        }
    }

    // ...
}    

这篇关于使用java泛型的责任链处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆