Singleton and Observer Pattern in Java

This has been done a million times before, but I just wanted to do it myself in Java.  Also has given me chance to use IntelliJ IDEA which is a great Java IDE on the mac – shame its not free,  but it does make doing java that bit more enjoyable so might be worth the $99.

Basic model.

  • Main class – Creates everything, sends messages which the observers should output
  • Feed and AnotherFeed – Observers registered to listen to the Alert object for messages, outputs any messages to console prefixed with their name.
  • Alert – Observable, receive message and notifies observers (feed and anotherfeed).  This follows the singleton pattern, so only one object is ever created.
  • Alerter – sends a message to Alert to trigger change.

Simple but effective (for a simple demo).

The main class contains the following:

//These will be used to listen for alerts and output them to the console
Feed f = new Feed();
AnotherFeed f2 = new AnotherFeed();

//Say they want the alerts
Alert.getInstance().addObserver(f);
Alert.getInstance().addObserver(f2);

//Call an object, which inturn calls Alert that something has happened.
Alerter.Alert(“DON’T PANIC”);
Alerter.Alert(“This is a test”);
Alerter.Alert(“Thanks”);

 

The alert class looks like this:

static Alert instance = null;

private Alert(){}

public static Alert getInstance()
{
if(instance == null)
{
instance = new Alert();
}

return instance;
}

public void postMessage(String message)
{
//push model
setChanged();
notifyObservers(message);
}

If you do not call setChanged(), then it doesn’t work.

Alerter looks like this

public static void Alert(String message)
{
Alert.getInstance().postMessage(message);
}

 

Feed and AnotherFeed do this:

public void update(Observable observable, Object object) {
System.out.println(“AnotherFeed Alert: ” + object.toString());
}

 

Because I send the message as a parameter of notifyObservers(), it gets sent to the observers as the object parameter.  This is the push model, in the pull model the observer would have had to gone and received the message for itself.

 

The final output to the console should be this:
AnotherFeed Alert: DON’T PANIC
Feed Alert: DON’T PANIC
AnotherFeed Alert: This is a test
Feed Alert: This is a test
AnotherFeed Alert: Thanks
Feed Alert: Thanks

Notice AnotherFeed outputs first, this is because it was added second, so the observers get called in the opposite order than what they where added.

 

Hope this helps someone, any questions leave a comment.

 

Code can be downloaded here : http://www.benhall.me.uk/code/Observer.zip

 

Leave a Reply

Your email address will not be published. Required fields are marked *