Created
June 15, 2016 03:29
-
-
Save KevinTyrrell/ce2ac0917ed3642b069effec43fc7fc2 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
public interface Listener | |
{ | |
public void fire(); | |
} |
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
public class SneakyNumber | |
{ | |
private int num; | |
// List of all listeners who want to know what happens to this object. | |
private LinkedList<Listener> listeners = new LinkedList<>(); | |
public SneakyNumber(int num) | |
{ | |
this.num = num; | |
} | |
public void setNum(int num) | |
{ | |
this.num = num; | |
// SOMEONE JUST CHANGED THE NUMBER, OH SH** ALERT EVERYONE THAT'S LISTENING. | |
for (Listener i : listeners) | |
i.fire(); | |
} | |
public int getNum() | |
{ | |
return num; | |
} | |
public void addListener(Listener var) | |
{ | |
listeners.add(var); | |
} | |
} |
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
public abstract class Test | |
{ | |
public static void main(String[] args) | |
{ | |
SneakyNumber x = new SneakyNumber(5); | |
x.addListener(new Listener() -> | |
{ | |
System.out.println("This number just changed, and now it's new value is " + x.getNum()); | |
} | |
x.setNum(10); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment