使用 java 泛型的责任链处理程序
我在 Java 中使用责任链设计模式。整个链代表对某些类型的对象的请求。链中的每个“处理程序”负责处理 1 种类型的请求单元。 所有请求基本上都以相同的方式处理,因此我尝试使“Handler”类通用。 因此,在 Handle 类中,我需要一个这样的方法(处理本身被简化,因为它只会混淆我的问题):
public class Handler<T>{
int required;
Handler<?> next;
public void handle(Object O){
if(o instanceof T){
required --;
}else{
next.handle(o);
}
}
}
问题是这样的实例是不可能的。因为类型 T 在运行时并未显式存储(或者这是我在互联网研究过程中所理解的)。所以我的问题是:最好的选择是什么?
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);
}
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过使用构造函数参数定义处理程序支持的类,使用泛型实现处理程序:
Implement handlers using generics by using a constructor parameter to define the class the handler supports:
看起来您实际上根本没有使用链,除非您在某些情况下基类和子类都启动事件。如果除非部分不适用,您可以
在根处理程序中执行类似 和 的操作:
It looks like you're not actually using a chain at all, unless you have some cases where both base and sub classes kick off events. If that unless part doesn't apply, you could do something like
and in root handler:
如果您对每个对象调用句柄,那么使用泛型的处理程序就没有意义。
要么实例化这样的类型处理程序:
要么定义一个抽象类处理程序并让特定子类处理特定类型,或者只是将事件传递到链。
另外,使用
实际上是一种反模式,您可能会违反 OOP 规则。
It doesn't make sense to have a handler using generics if you call handle on every object.
Either you instantiate an handler for type like this:
or you define a abstract class handler and let the specific subclass to handle specific type or just pass the event to the chain.
Also using
is really an antipattern and you can break OOP rules.
这会很难看,但你可以尝试这个:
It would be ugly, but you could try this: