使用混合POJOS处理集合,每个POJO使用不同的处理程序 [英] Handling collections with mixed POJOS, with different handler for each POJO

查看:49
本文介绍了使用混合POJOS处理集合,每个POJO使用不同的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下问题找到一种优雅的OOP解决方案.

I'm trying to find an elegant OOP solution for the following problem.

假设我们有一个POJOS集合,在这种情况下是事件,其中每个POJO可能是不同的类.我们需要对每个POJO类(或类型)使用不同的规则来处理此集合.

Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).

一个基本的假设是,我们不能用适当的处理程序来装饰POJO,因为我们无法控制POJO的生成,并按原样接收集合.因此,任何对此的机制都属于同一陷阱.但是,项目3 stil处理这种可能性.

A basic assumption is that we can't decorate the POJOs with appropriate handlers, since we don't control their generation, and receive the collection as is. Thus, any mechanism for this falls into the same trap. However, item 3 stil deals with this possibility.

有一些可能的解决方案,一些非常丑陋,一些更优雅但更复杂:

There are some possible solutions, some very ugly, some more elegant but complicated:

  1. 最明显,最丑陋的解决方案是使用instanceOf运算符将POJO传递给处理程序.
  2. 对1的更好修改是对链式调度程序使用责任链,因此新类型只需要一个新的调度程序.但是,每个调度程序仍然需要instanceOf.
  3. 创建增强的对象,而不是POJOS,其中每个对象都包含对其处理程序的引用.这会在POJO和我们的处理器之间建立耦合.
  4. 创建一个调度程序服务(我知道如何用Java正确地做到这一点),该服务将处理程序注册到特定的事件类,并使用泛型(Typesafe容器,如有效的Java)将事件调度到处理程序.

4是最优雅的,但是我想知道是否还有更好的主意.

4 is the most elegant, but I was wondering if there are any better ideas.

推荐答案

#4的简化:

使用Map存储每个事件类的处理程序.

Use a Map to store the handler for each event class.

Map<Class, Handler> classHandlers = new HashMap<Class, Handler>();
classHandlers.put(EventA.class, new EventAHandler());
classHandlers.put(EventB.class, new EventBHandler());

现在使用事件的类来获取事件的处理程序.

Now use the class of the event to get the handler for the event.

Handler handler = classHandlers.get(event.getClass());
handler.handle(event);

当然,这需要在编码时了解所有可能的事件类,因此不如外部事件分配器灵活.

Of course this requires knowledge of all possible event classes at coding time and is thus less flexible than an external event dispatcher.

这篇关于使用混合POJOS处理集合,每个POJO使用不同的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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