Created
December 29, 2013 17:24
-
-
Save matklad/8172568 to your computer and use it in GitHub Desktop.
Pattern matching of a poor man
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 java.io.Serializable; | |
public class TwoAvgProtocol implements Serializable { | |
interface MessageReceiver { | |
public void onHave(double val); | |
public void onAdjust(double delta); | |
} | |
static abstract class Message { | |
protected abstract int getTag(); | |
public void receive(MessageReceiver receiver) { | |
switch (getTag()) { | |
case 1: | |
receiver.onHave(((Have)this).val); | |
break; | |
case 2: | |
receiver.onAdjust(((Adjust)this).delta); | |
break; | |
default: | |
assert false; | |
} | |
} | |
} | |
static class Have extends Message { | |
public double val; | |
public Have(double val) { | |
this.val = val; | |
} | |
@Override | |
protected int getTag() { | |
return 1; | |
} | |
} | |
static class Adjust extends Message { | |
public double delta; | |
public Adjust(double delta) { | |
this.delta = delta; | |
} | |
@Override | |
protected int getTag() { | |
return 2; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment