廣告

2015年3月17日 星期二

[java][designPattern] observer pattern

這個用法其實 在android 的 listView or gridview就有被使用
這兩個元件用完都需要呼叫 notifydatachange() 來更新畫面

Color.java
package com.test.observerpattern;

public abstract class Color {
 protected DrawBoard drawBoard;
 public abstract void update();
}




DrawBoard.java
package com.test.observerpattern;

import java.util.ArrayList;
import java.util.List;

public class DrawBoard {
 private List colors = new ArrayList();
 private String state;

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
  notifyAllObservers();
 }

 public void addColor(Color observer) {
  colors.add(observer);
 }

 public void notifyAllObservers() {
  for (Color color : colors) {
   color.update();
  }
 }
}




Pain1.java
package com.test.observerpattern;

public class Pain1 extends Color {
 public Pain1(DrawBoard drawBoard) {
  this.drawBoard = drawBoard;
  this.drawBoard.addColor(this);
 }

 @Override
 public void update() {
  System.out.println("Pain1's color is :"+drawBoard.getState());
 }
}




Pain2.java
package com.test.observerpattern;

public class Pain2 extends Color {
 public Pain2(DrawBoard drawBoard) {
  this.drawBoard = drawBoard;
  this.drawBoard.addColor(this);
 }

 @Override
 public void update() {
  System.out.println("Pain2's color is :"+drawBoard.getState());
 }
}




testObserverPattern.java
package com.test.observerpattern;

public class testObserverPattern {
    public static void main(String[] args) {
     DrawBoard drawBoard = new DrawBoard();

       new Pain1(drawBoard);
       new Pain2(drawBoard);

       System.out.println("Change pain color to red"); 
       drawBoard.setState("red");
       System.out.println("Change pain color to white"); 
       drawBoard.setState("white");
    }
 }



console
Change pain color to red
Pain1's color is :red
Pain2's color is :red
Change pain color to white
Pain1's color is :white
Pain2's color is :white



沒有留言:

張貼留言