Skip to content

Instantly share code, notes, and snippets.

@Vitalik549
Last active December 6, 2017 15:20
Show Gist options
  • Select an option

  • Save Vitalik549/dca035c0a527385dd1ab79fb3c40be01 to your computer and use it in GitHub Desktop.

Select an option

Save Vitalik549/dca035c0a527385dd1ab79fb3c40be01 to your computer and use it in GitHub Desktop.
java observer pattern (listener)
Observer pattern is used when there is one-to-many relationship between objects
such as if one object is modified, its depenedent objects are to be notified automatically.
Observer pattern falls under behavioral pattern category.
public class Application implements ComputerListener {
private static int counter = 0;
private int id;
Application(){ id = ++counter; }
@Override
public void onStart() {
System.out.println("app " + id + " launched...");
}
@Override
public void onStop() {
System.out.println("app " + id + " saving before comp down...");
}
}
import java.util.ArrayList;
import java.util.List;
public class Computer {
List<ComputerListener> listeners = new ArrayList<>();
void start(){
System.out.println("started...");
listeners.forEach(ComputerListener::onStart);
}
void stop(){
System.out.println("comp is going to stop, notifying everyone!");
listeners.forEach(ComputerListener::onStop);
System.out.println("computer stopped!");
}
}
public interface ComputerListener {
void onStart();
void onStop();
}
public class Main {
public static void main(String[] args) {
Computer computer = new Computer();
computer.listeners.add(new Application());
computer.listeners.add(new Application());
computer.start();
computer.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment