java常用設計模式-觀察者模式

來源:互聯網
上載者:User

標籤:設計模式   狀態   訂閱   觀察   package   date   取消   通知   角色   

觀察者模式:

設計到的角色:

主題:是一個介面,同時必須包含一個觀察者列表,必須有添加,刪除,通知觀察者的方法

具體主題:主題的實作類別

觀察者:也是介面,介面中需要定義接到通知之後的操作

具體觀察者:觀察者的實作類別,同時觀察者要訂閱主題則需要註冊,即必須要添加到主題的觀察者列表中,取消訂閱則是刪除

當主題的狀態發生變化的時候,所有的觀察者都得到通知

 

主題:

package com.design2;

public interface SubjectInterface {
void add(ObserverInterface observer);
void delete(ObserverInterface observer);
void notifyObserver();
void giveMess(String mess);
}

具體主題:

package com.design2;

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

public class Subject implements SubjectInterface {
List<ObserverInterface> observerList;
String mess;
boolean isNotify;
public Subject(){
observerList = new ArrayList<ObserverInterface>();
mess = "";
isNotify = false;
}
@Override
public void add(ObserverInterface observer) {
if (observer != null && !observerList.contains(observer)) {
observerList.add(observer);
}

}

@Override
public void delete(ObserverInterface observer) {
if (observerList.contains(observer)) {
observerList.remove(observer);
}
}

@Override
public void notifyObserver() {
if (isNotify) {
for (ObserverInterface object : observerList) {
object.update(mess);
}
}
}

@Override
public void giveMess(String message) {
if (mess.equals(message)) {
isNotify = false;
} else {
mess = message;
isNotify = true;
}
}
}

觀察者介面:

package com.design2;

public interface ObserverInterface {
void update(String mess);
}

 

觀察者:

package com.design2;

public class Observer implements ObserverInterface {
private String name;
private SubjectInterface subject;
public Observer(String name,SubjectInterface subject){
this.name = name;
subject.add(this);
}

@Override
public void update(String mess) {
System.out.println(name + "接受的訊息:" + mess);
}

}

 

測試:

package com.design2;

public class Application {
public static void main(String[] args) {
SubjectInterface subject = new Subject();
ObserverInterface zhangsan = new Observer("zhangsan", subject);
ObserverInterface lisi = new Observer("zhangsan", subject);
subject.giveMess("123");
subject.notifyObserver();
subject.giveMess("123");
subject.notifyObserver();
subject.giveMess("456");
subject.notifyObserver();
}
}

 

java常用設計模式-觀察者模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.