Archive

Archive for February, 2016

Observer Pattern

February 20, 2016 Leave a comment

Observer pattern is one to many dependency between object so when object changes state  so all of it dependents are notified. In observer pattern the object that watch on the state of another object are called Observer and the object that is being watched is called Subject / Observable.

Observer Pattern

Observer Pattern

Here is example.

Observer.java

public interface Observer {
 public void update();
}

Dress.java

public class Dress implements Observable {

 private List<Observer> observers;
 private int stock;

 public Dress() {
 observers = new ArrayList<Observer>();
 }

 public void addObserver(Observer observer) {
 observers.add(observer);
 }

 public void notifyObserver() {
 if (getStock() < 1) {
 for (Observer observer : observers) {
 observer.update();
 }
 }
 }

 public int getStock() {
 return stock;
 }

 public void setStock(int stock) {
 this.stock = stock;
 notifyObserver();
 }
}

Observable.java

public interface Observable {
 public void addObserver(Observer observer);
 public void notifyObserver();
}

Buyer.java

public class Buyer implements Observer {

 private String name;
 private String job;

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getJob() {
 return job;
 }

 public void setJob(String job) {
 this.job = job;
 }

 public void update() {
 System.out.println("Name " + name + " Job " + job + " get notifcation");
 }

}

Supplier.java

 public class Supplier implements Observer {
 private String name;
 private String address;

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 public void update() {
 System.out.println("Supplier " + name + " Address " + address + " get notifcation");
 }
} 
Categories: Java Tags: , ,