Reputation: 19582
I have the following design:
I have a series of classes that process some objects let's say events.
Each class processes only a specific type of event.
Now when I have these objects/events that need processing I loop over all events and then loop over all the processors until I am done.
The only optimization I did is that if an event is not the proper for a class return immediatelly.
How could I change my design to get rid of this O(N^2)
loop? Or perhaps it isn't worth changing and it is ok like this?
Update
Example algorith-code:
for(Event e:events) {
for(Processor p:processors) {
p.process(e);
}
}
Upvotes: 1
Views: 99
Reputation: 15
If you have a specific processor for every event type you can create a Map (EventClass -> EventProcessor) and then you can remove one loop - O(N) now.
Upvotes: 0
Reputation: 245479
You could implement the Observer pattern. Each processor would observe the objects and listen for the event. The processor would decide whether or not to handle the event based on what type of event it was.
Java actually has two interfaces explicitly meant for this pattern: Observable
and Observer
.
Upvotes: 5