Skip to content

Instantly share code, notes, and snippets.

@KevinTyrrell
Created June 15, 2016 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinTyrrell/ce2ac0917ed3642b069effec43fc7fc2 to your computer and use it in GitHub Desktop.
Save KevinTyrrell/ce2ac0917ed3642b069effec43fc7fc2 to your computer and use it in GitHub Desktop.
public interface Listener
{
public void fire();
}
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);
}
}
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