疊代器模式
關注
資料周遊
,且分離資料與疊代器,實作解耦
一、需求
編寫程式展示一個學校院系結構:需求是這樣,要在一個頁面中展示出學校的院系組成,一個學校有多個學院, 一個學院有多個系。如圖:
二、傳統的設計方案(類圖)
三、傳統的方式的問題分析
1)将學院看做是學校的子類,系是學院的子類,這樣實際上是站在
組織大小
來進行分層次的
2)實際上我們的要求是 :在一個頁面中展示出學校的院系組成,一個學校有多個學院,一個學院有多個系, 是以這種方案,不能很好實作的
周遊的操作
3)解決方案:=>
疊代器模式
四、疊代器模式基本介紹
- 基本介紹
1)(Iterator Pattern)是常用的設計模式,屬于
疊代器模式
2)如果我們的
行為型模式
,有數組,還有 java 的集合類,或者還有其他方式,當用戶端要
集合元素是用不同的方式實作的
周遊這些集合元素
的時候就要使用多種周遊方式,而且還會暴露元素的内部結構,可以考慮使用疊代器模式解決。
3)疊代器模式,提供一種周遊集合元素的統一接口,用一緻的方法周遊集合元素,不需要知道集合對象的底層表示,即:不暴露其内部的結構。
- 原理類圖
- 對原理類圖的說明-即(疊代器模式的角色及職責)
1)Iterator : 疊代器接口,是系統提供,含義 hasNext(), next(), remove()
2)ConcreteIterator : 具體的疊代器類,管理疊代
3)Aggregate : 一個統一的聚合接口, 将用戶端和具體聚合解耦
4)ConcreteAggreage : 具體的聚合持有對象集合, 并提供一個方法,傳回一個疊代器, 該疊代器可以正确周遊集合
5)Client : 用戶端, 通過 Iterator 和 Aggregate 依賴子類
五、疊代器模式應用執行個體
1)應用執行個體要求
編寫程式展示一個學校院系結構:需求是這樣,要在一個頁面中展示出學校的院系組成,一個學校有多個學院, 一個學院有多個系。
2)設計思路分析
Iterator:輸出的方式,周遊方式
College:真正需要周遊的集合,資料
3)代碼實作
主函數
public class Client {
public static void main(String[] args) {
//建立學院
List<College> collegeList = new ArrayList<College>();
ComputerCollege computerCollege = new ComputerCollege();
InfoCollege infoCollege = new InfoCollege();
collegeList.add(computerCollege);
//collegeList.add(infoCollege);
OutPutImpl outPutImpl = new OutPutImpl(collegeList);
outPutImpl.printCollege();
}
}
College學院接口
//College學院接口
public interface College {
//擷取學院名
public String getName();
//增加系的方法
public void addDepartment(String name, String desc);
//傳回一個疊代器,周遊
public Iterator createIterator();
}
ComputerCollege計算機學院
//計算機學院
public class ComputerCollege implements College {
Department[] departments;
int numOfDepartment = 0 ;// 儲存目前數組的對象個數
public ComputerCollege() {
departments = new Department[5];
addDepartment("Java 專業", " Java 專業 ");
addDepartment("PHP 專業", " PHP 專業 ");
addDepartment("大資料專業", " 大資料專業 ");
}
@Override
public String getName() {
return "計算機學院";
}
@Override
public void addDepartment(String name, String desc) {
Department department = new Department(name, desc);
departments[numOfDepartment] = department;
numOfDepartment += 1;
}
@Override
public Iterator createIterator() {
return new ComputerCollegeIterator(departments);
}
}
ComputerCollegeIterator
public class ComputerCollegeIterator implements Iterator {
//這裡我們需要 Department 是以怎樣的方式存放=>數組
Department[] departments;
int position = 0; //周遊的位置
//構造器
public ComputerCollegeIterator(Department[] departments) {
this.departments = departments;
}
//判斷是否還有下一個元素
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if(position >= departments.length || departments[position] == null) {
return false;
}else {
return true;
}
}
@Override
public Object next() {
Department department = departments[position];
position += 1;
return department;
}
//删除的方法,預設空實作
public void remove() {}
}
Department
//系
@Data
public class Department {
private String name;
private String desc;
public Department(String name, String desc) {
super();
this.name = name;
this.desc = desc;
}
}
InfoColleageIterator
public class InfoColleageIterator implements Iterator {
List<Department> departmentList; // 資訊工程學院是以 List 方式存放系
int index = -1;//索引
public InfoColleageIterator(List<Department> departmentList) {
this.departmentList = departmentList;
}
//判斷 list 中還有沒有下一個元素
@Override
public boolean hasNext() {
if(index >= departmentList.size() - 1) {
return false;
} else {
index += 1;
return true;
}
}
@Override
public Object next() {
return departmentList.get(index);
}
// 空 實 現
remove public void remove() {}
}
InfoCollege
public class InfoCollege implements College {
List<Department> departmentList;
public InfoCollege() {
departmentList = new ArrayList<Department>();
addDepartment("資訊安全專業", " 資訊安全專業 ");
addDepartment("網絡安全專業", " 網絡安全專業 ");
addDepartment("伺服器安全專業", " 伺服器安全專業 ");
}
@Override
public String getName() {
return "資訊工程學院";
}
@Override
public void addDepartment(String name, String desc) {
Department department = new Department(name, desc);
departmentList.add(department);
}
@Override
public Iterator createIterator() {
return new InfoColleageIterator(departmentList);
}
}
OutPutImpl
public class OutPutImpl {
//學院集合
List<College> collegeList;
public OutPutImpl(List<College> collegeList) {
this.collegeList = collegeList;
}
//周遊所有學院,然後調用 printDepartment 輸出各個學院的系
public void printCollege() {
//從 collegeList 取出所有學院, Java 中的 List 已經實作 Iterator
Iterator<College> iterator = collegeList.iterator();
while(iterator.hasNext()) {
//取出一個學院
College college = iterator.next();
System.out.println("=== "+college.getName() +"=====" );
printDepartment(college.createIterator()); //得到對應疊代器
}
}
//輸出 學院輸出 系
public void printDepartment(Iterator iterator) {
while(iterator.hasNext()) {
Department d = (Department)iterator.next();
System.out.println(d.getName());
}
}
}
六、疊代器模式的注意事項和細節
- 優點
- 提供一個
,客戶不用再考慮聚合的類型,使用一種方法就可以周遊對象了。統一的方法周遊對象
2)隐藏了聚合的内部結構,用戶端要周遊聚合的時候隻能取到疊代器,而不會知道聚合的具體組成。
3)提供了一種設計思想,就是一個類應該隻有一個引起變化的原因(叫做單一責任原則)。在聚合類中,我們把疊代器分開,就是
要把管理對象集合和周遊對象集合的責任分開
, 這樣一來集合改變的話,隻影響到聚合對象。而如果周遊方式改變的話,隻影響到了疊代器。
4)當要展示一組相似對象,或者
周遊
一組相同對象時使用, 适合使用疊代器模式
- 缺點
每個聚合對象都要一個疊代器,會生成多個疊代器不好管理類
觀察者模式
關注
一對多的訂閱形式
,分離觀察者(訂閱者)和資料提供者,實作解耦
一、天氣預報項目需求,具體要求如下:
1)氣象站可以将每天測量到的溫度,濕度,氣壓等等以公告的形式釋出出去(比如釋出到自己的網站或第三方)。
2)需要設計開放型 API,便于其他第三方也能接入氣象站擷取資料。
3)提供溫度、氣壓和濕度的接口
4)測量資料更新時,要能實時的通知給第三方
二、 普通方案
- 傳統的設計方案
- 代碼實作
WeatherData主動推送的方式
CurrentConditions了解為應用網址
主函數:
public class Client {
public static void main(String[] args) {
//建立接入方 currentConditions
CurrentConditions currentConditions = new CurrentConditions();
//建立 WeatherData 并将 接入方 currentConditions 傳遞到 WeatherData 中
WeatherData weatherData = new WeatherData(currentConditions);
//更新天氣情況
weatherData.setData(30, 150, 40);
//天氣情況變化
System.out.println("============天氣情況變化=============");
weatherData.setData(40, 160, 20);
}
}
CurrentConditions:
/**
* 顯示目前天氣情況(可以了解成是氣象站自己的網站)
* @author Administrator
*
*/
public class CurrentConditions {
// 溫度,氣壓,濕度
private float temperature;
private float pressure;
private float humidity;
//更新 天氣情況,是由 WeatherData 來調用,我使用推送模式
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
//顯示
public void display() {
System.out.println("***Today mTemperature: " + temperature + "***");
System.out.println("***Today mPressure: " + pressure + "***");
System.out.println("***Today mHumidity: " + humidity + "***");
}
}
WeatherData:
/**
* 類是核心
* 1. 包含最新的天氣情況資訊
* 2. 含有 CurrentConditions 對象
* 3. 當資料有更新時,就主動的調用 CurrentConditions 對象 update 方法(含 display), 這樣他們(接入方)就看到最新的資訊
* @author Administrator
*
*/
public class WeatherData {
private float temperatrue;
private float pressure;
private float humidity;
//加入新的第三方
private CurrentConditions currentConditions;
public WeatherData(CurrentConditions currentConditions) {
this.currentConditions = currentConditions;
}
public float getTemperature() {
return temperatrue;
}
public float getPressure() {
return pressure;
}
public float getHumidity() {
return humidity;
}
public void dataChange() {
//調用 接入方的 update
currentConditions.update(getTemperature(), getPressure(), getHumidity());
}
//當資料有更新時,就調用 setData
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//調用 dataChange, 将最新的資訊 推送給 接入方 currentConditions
dataChange();
}
}
- 問題分析
1)其他第三方接入氣象站擷取資料的問題
2)
無法在運作時動态的添加第三方 (新浪網站)
3)違反 ocp 原則=>
觀察者模式
//在 WeatherData 中,當增加一個第三方,都需要建立一個對應的第三方的公告闆對象,并加入到 dataChange, 不利于維護,也不是動态加入
public void dataChange() {
currentConditions.update(getTemperature(), getPressure(), getHumidity());
}
三、 觀察者模式原理
- 觀察者模式類似訂牛奶業務
1)奶站/氣象局:Subject
2)使用者/第三方網站:Observer (觀察者)
- Subject:登記注冊、移除和通知 ---->相當于上面的WeatherData
1)registerObserver: 注 冊
2)removeObserver: 移 除
3)notifyObservers() 通知所有的注冊的使用者,根據不同需求,可以是更新資料,讓使用者來取,也可能是實施推送, 看具體需求定
- Observer:接收輸入(觀察者)
-
觀察者模式:
對象之間
的一種設計方案,被依賴的對象為 Subject,依賴的對象為 Observer,Subject通知 Observer 變化, 比如這裡的奶站是 Subject,是 1 的一方。使用者時 Observer,是多的一方。多對一依賴
四、觀察者模式解決天氣預報需求
1、 類圖說明
2、代碼實作
BaiduSite
public class BaiduSite implements Observer {
// 溫度,氣壓,濕度
private float temperature;
private float pressure;
private float humidity;
// 更新 天氣情況,是由 WeatherData 來調用,我使用推送模式
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
// 顯 示
public void display() {
System.out.println("===百度網站====");
System.out.println("***百度網站 氣溫 : " + temperature + "***");
System.out.println("***百度網站 氣壓: " + pressure + "***");
System.out.println("***百度網站 濕度: " + humidity + "***");
}
}
主函數
public class Client {
public static void main(String[] args) {
//建立一個 WeatherData
WeatherData weatherData = new WeatherData();
//建立觀察者
CurrentConditions currentConditions = new CurrentConditions();
BaiduSite baiduSite = new BaiduSite();
// 注 冊 到 weatherData
weatherData.registerObserver(currentConditions);
weatherData.registerObserver(baiduSite);
//測試
System.out.println("通知各個注冊的觀察者, 看看資訊");
weatherData.setData(10f, 100f, 30.3f);
weatherData.removeObserver(currentConditions);
System.out.println("==========================");
//測試
System.out.println("通知各個注冊的觀察者, 看看資訊");
weatherData.setData(10f, 100f, 30.3f);
}
}
CurrentConditions
public class CurrentConditions implements Observer {
// 溫度,氣壓,濕度
private float temperature;
private float pressure;
private float humidity;
// 更新 天氣情況,是由 WeatherData 來調用,我使用推送模式
public void update(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
// 顯 示
public void display() {
System.out.println("***Today mTemperature: " + temperature + "***");
System.out.println("***Today mPressure: " + pressure + "***");
System.out.println("***Today mHumidity: " + humidity + "***");
}
}
Observer
//觀察者接口,有觀察者來實作
public interface Observer {
public void update(float temperature, float pressure, float humidity);
}
Subject
//接口, 讓 WeatherData 來實作
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
WeatherData
/**
* 類是核心
* 1. 包含最新的天氣情況資訊
* 2. 含有 觀察者集合,使用 ArrayList 管理
* 3. 當資料有更新時,就主動的調用 ArrayList, 通知所有的(接入方)就看到最新的資訊
* @author Administrator
*
*/
@Data
public class WeatherData implements Subject {
private float temperatrue;
private float pressure;
private float humidity;
//觀察者集合
private ArrayList<Observer> observers;
//加入新的第三方
public WeatherData() {
observers = new ArrayList<Observer>();
}
public void dataChange() {
//調用 接入方的 update
notifyObservers();
}
//當資料有更新時,就調用 setData
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//調用 dataChange, 将最新的資訊 推送給 接入方 currentConditions
dataChange();
}
//注冊一個觀察者
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
//移除一個觀察者
@Override
public void removeObserver(Observer o) {
if(observers.contains(o)) {
observers.remove(o);
}
}
//周遊所有的觀察者,并通知
@Override
public void notifyObservers() {
//周遊集合
for(int i = 0; i < observers.size(); i++) {
//根據每個訂閱的觀察者對應的資料
observers.get(i).update(this.temperatrue, this.pressure, this.humidity);
}
}
}
3、觀察者模式的好處
1)觀察者模式設計後,會以集合的方式來管理使用者(Observer),包括注冊,移除和通知。
2)這樣,我們
這裡可以了解成一個新的公告闆),就
增加觀察者(
, 遵守了 ocp 原則。
不需要去修改核心類 WeatherData 不會修改代碼