Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Observer Pattern for Games: Example
import java.util.Observable;
public class Main {
public static void main(String[] args) {
NonPlayerCharacter Bella = NonPlayerCharacter.getNPC();
TattleTaleObserver tattleTaleObserver = new TattleTaleObserver(Bella);
Bella.addObserver(tattleTaleObserver);
Bella.setDeathStatus(false);
Bella.setDeathStatus(false);
Bella.setDeathStatus(false);
Bella.setDeathStatus(true);
}
}
import java.util.Observable;
/**
* Created by gjvongraves on 3/13/17.
*/
public class NonPlayerCharacter extends Observable{
/* Bella is in control over many aspects of the game's world.
Specifically, she makes sure the user is not attacked by random NPCs.
There is only one NonPlayerCharacter. Hence, she will be a singleton
*/
private final String NPC_NAME = "Bella";
private boolean isDead = false;
private static NonPlayerCharacter NPC = null;
//Singleton. Unaccesible outside the class.
private NonPlayerCharacter() {}
public static NonPlayerCharacter getNPC()
{
if(NPC == null)
{
return new NonPlayerCharacter();
}
else{
//She is dead. Or can't generate more than one.
return null;
}
}
public boolean getDeathStatus()
{
return this.isDead;
}
public void setDeathStatus(boolean didKill)
{
this.isDead = didKill;
setChanged();
notifyObservers();
}
}
import java.util.Observable;
import java.util.Observer;
/**
* Created by gjvongraves on 3/13/17.
*/
public class TattleTaleObserver implements Observer {
private NonPlayerCharacter Bella;
public TattleTaleObserver(NonPlayerCharacter NPC)
{
this.Bella = NPC;
}
@Override
public void update(Observable object, Object arg) {
Bella = (NonPlayerCharacter)object;
if(Bella.getDeathStatus())
{
System.out.println("Report: Bella is dead.");
}else {
System.out.println("Report: Bella is alive. Thank goodness.." );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.