Search code examples
javadesign-patternsdelegation

Delegation Event Model pattern Java


When applying this pattern Delegation Event Model, is it correct to put ALL the code in the fire... methods and pass the parameters from the public method?

Like this

public void addBananas(Banana banana) {
    fireBananaAdded(banana);  
}

private void fireBananaAdded(Banana banana) {
    //Create event etc and add banana to list here
}

Or should I have the add to list part in this example in the addBananas method instead? Because if I do it this way I will not have the opportunity to "attach" the banana object to the event-object which will be passed to the listeners, right?


Solution

  • I would put as much logic in addBanana() that is related to actually adding the Banana as I can.

    When I'm done with addBanana(), I would call fireBananaAdded() which would generate the appropriate BananaAddedEvent and send it to the BananaAddedListeners (or just BananaListeners, which ever you have.)

    To put the ADD logic in the FIRE method is simply, well, BANANAS!

    public void addBananas(Banana banana) {
        if(BananaHolder.hasRoom()) {
            BananaHolder.add(banana);
            fireBananaAdded(banana);  
        }
    }
    
    private void fireBananaAdded(Banana banana) {
        BananaAddedEvent event = new BananaAddedEvent(banana);
        for(BananaListener listener : listenersByType(Banana.class)) {
            listener.bananaAdded(event);
        }
    }