Created
October 7, 2016 18:47
-
-
Save collinvandyck/174e475d524f9f8de0dbfc604347afa7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.librato.alerts.IEmitter; | |
public class DoubleDispatch { | |
static IEmitter emitter; | |
public static void main(String[] args) { | |
IMessage messageA = new MessageA(); | |
IMessage messageB = new MessageB(); | |
// without double dispatch | |
emitter.emit(new Payload(messageA)); | |
emitter.emit(new Payload(messageB)); | |
// with double dispatch | |
messageA.emit(emitter); | |
messageB.emit(emitter); | |
} | |
static class Payload { | |
public Payload(IMessage message) { | |
// has to figure out what data to pull out of message | |
} | |
public Payload(MessageA message) { | |
// initializes using specific MessageA data | |
} | |
public Payload(MessageB message) { | |
// initializes using specific MessageB data | |
} | |
} | |
interface IEmitter { | |
void emit(Payload payload); | |
} | |
/* | |
* Two implementations of IMessage, both know how to emit themselves | |
* to an IEmitter | |
*/ | |
interface IMessage { | |
void emit(IEmitter emitter); | |
} | |
static class MessageA implements IMessage { | |
@Override | |
public void emit(IEmitter emitter) { | |
// emit, but build the payload based on the concrete type | |
emitter.emit(new Payload(this)); | |
} | |
} | |
static class MessageB implements IMessage { | |
@Override | |
public void emit(IEmitter emitter) { | |
// emit, but build the payload based on the concrete type | |
emitter.emit(new Payload(this)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment