1. 程式人生 > >觀察者設計模式

觀察者設計模式

實現 per 合並 一個 num ride blog 通知 elf

1.觀察者接口及實現類

//一個Observer接口:
1.public interface Observer {  
2.    public void update();  
3.}  

//兩個實現類:
1.public class Observer1 implements Observer {  
2.  
3.    @Override  
4.    public void update() {  
5.        System.out.println("observer1 has received!");  
6.    }  
7.}  
1.public class Observer2 implements
Observer { 2. 3. @Override 4. public void update() { 5. System.out.println("observer2 has received!"); 6. } 7. 8.}

2.訂閱者接口及實現類

//訂閱者接口
public interface Subject {  
2.      
3.    /*增加觀察者*/  
4.    public void add(Observer observer);  
5.      
6.    /*刪除觀察者*/  
7.    public
void del(Observer observer); 8. 9. /*通知所有的觀察者*/ 10. public void notifyObservers(); 11. 12. /*自身的操作*/ 13. public void operation(); 14.} //實現接口的抽象類 1.public abstract class AbstractSubject implements Subject { 2. 3. private Vector<Observer> vector = new Vector<Observer>();
4. @Override 5. public void add(Observer observer) { 6. vector.add(observer); 7. } 8. 9. @Override 10. public void del(Observer observer) { 11. vector.remove(observer); 12. } 13. 14. @Override 15. public void notifyObservers() { 16. Enumeration<Observer> enumo = vector.elements();//放入觀察者的集合,並循環遍歷來調用(通知)觀察者的update()方法 17. while(enumo.hasMoreElements()){ 18. enumo.nextElement().update(); 19. } 20. } 21.} //繼承抽象類的具體實現類 1.public class MySubject extends AbstractSubject { 2. 3. @Override 4. public void operation() { 5. System.out.println("update self!"); 6. notifyObservers(); 7. } 8. 9.}

3.測試使用

//將所有 的觀察者放入集合並調用訂閱函數
public class ObserverTest {  
2.  
3.    public static void main(String[] args) {  
4.        Subject sub = new MySubject();  
5.        sub.add(new Observer1());  
6.        sub.add(new Observer2());  
7.          
8.        sub.operation();  
9.    }  
10.  
11.} 

輸出結果

update self!
observer1 has received!
observer2 has received!

觀察者設計模式