设计模式观察者模式_观察者设计模式教程
設(shè)計(jì)模式觀察者模式
Design pattern is one of the most important but feared aspects of software engineering especially for people who are new to the topic. When I started my associate architecture course, I myself had a hard time understanding the idea of different software design patterns.
設(shè)計(jì)模式是軟件工程中最重要但又令人擔(dān)憂的方面之一,特別是對(duì)于剛接觸該主題的人員而言。 當(dāng)我開(kāi)始輔助架構(gòu)課程時(shí),我自己很難理解不同軟件設(shè)計(jì)模式的思想。
Main reason of difficulty in learning design pattern is that the terms which are used in the patterns are pretty hard to understand at first. As a developer, it’s easier for programmers to understand the idea from code, then those terminologies don’t seem that much complicated. So, this is a trial to blend both theory and code together.
學(xué)習(xí)設(shè)計(jì)模式困難的主要原因是,一開(kāi)始很難理解設(shè)計(jì)模式中使用的術(shù)語(yǔ)。 作為開(kāi)發(fā)人員,程序員更容易從代碼中理解想法,然后這些術(shù)語(yǔ)似乎并不那么復(fù)雜。 因此,這是將理論和代碼融合在一起的嘗試。
And the first part starts with an important pattern, Observer design pattern.
第一部分從一個(gè)重要的模式開(kāi)始,即觀察者設(shè)計(jì)模式。
According to the Wikipedia, observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
根據(jù)Wikipedia的介紹,觀察者模式是一種軟件設(shè)計(jì)模式,在該模式中,稱為主題的對(duì)象會(huì)維護(hù)其依賴者的列表(稱為觀察者),并通常通過(guò)調(diào)用其方法之一來(lái)自動(dòng)將狀態(tài)更改通知他們。
The definition is a bit difficult to understand if you are first-timer to design patterns. So let’s think about an example. Nowadays it’s the era of digital media. We all know about group subscriptions and notification on Facebook or any social media. So, when you’re trying to picture the Observer pattern, a Group subscription service with its group being the publisher and users as subscribers is a good way to visualize the pattern.
如果您是第一次設(shè)計(jì)模式, 那么定義將很難理解。 因此,讓我們考慮一個(gè)示例。 如今,這是數(shù)字媒體的時(shí)代。 我們都知道團(tuán)體訂閱以及在Facebook或任何社交媒體上的通知。 因此,當(dāng)您嘗試描繪觀察者模式時(shí),以其組為發(fā)布者而用戶為訂閱者的組訂閱服務(wù)是可視化該模式的好方法 。
Figure 1: Group subscription and notification as example of observer pattern圖1:組訂閱和通知作為觀察者模式的示例You follow a group of your interest to get updates of the group. So you are a subscriber/follower of that group. Now if a post is updated, a notification from the group will appear in your timeline. You are the subscriber and the group is the publisher and the group has your profile information so that when a new post is updated, it sends you a notification. This kind of subscription mechanism is where we need observer design pattern.
您關(guān)注您感興趣的組以獲取該組的更新。 因此,您是該群組的訂閱者/關(guān)注者。 現(xiàn)在,如果帖子已更新,則來(lái)自該群組的通知將出現(xiàn)在您的時(shí)間軸中。 您是訂戶,該組是發(fā)布者,該組具有您的個(gè)人資料信息,以便在更新新帖子時(shí)向您發(fā)送通知。 這種 訂閱機(jī)制 是我們需要觀察者設(shè)計(jì)模式的地方。
If you know about MVC pattern, “View” part of Model-View-Controller can be described as observer. When UI element changes state, all its dependents are notified and updated automatically.
如果您了解MVC模式,則可以將Model-View-Controller的“視圖”部分描述為觀察者。 當(dāng)UI元素更改狀態(tài)時(shí),將自動(dòng)通知其所有依賴項(xiàng)并進(jìn)行更新。
For understanding observer we need to divide observer pattern into three parts. There are three parts of observer pattern.
為了理解觀察者,我們需要將觀察者模式分為三部分。 觀察者模式包括三個(gè)部分 。
i) Subject/Publisher
i)主題/發(fā)布者
ii) Observer/Subscriber, and
ii)觀察者/訂閱者,以及
iii) Client.
iii)客戶。
In observer pattern, we call the publisher the SUBJECT and the subscribers the OBSERVERS. Client-side means just the main function, so no need to worry about that. So we may think like :
在觀察者模式中,我們將發(fā)布者稱為SUBJECT ,將訂閱者稱為OBSERVERS 。 客戶端只是主要功能,因此無(wú)需擔(dān)心。 因此,我們可能會(huì)這樣想:
Publishers + Subscribers = Observer Pattern.
發(fā)布者+訂閱者=觀察者模式。
Learning design pattern by just reading theory is a bit tough because of different terminology used in a pattern. For example in this pattern, we have subject, observer and client. It’s easier for programmers to understand the idea from code. So I will describe the pattern with code. The example code is in java, you can use any object-oriented language of your preference. Maybe later I will try to edit the article with other language code links.
僅通過(guò)閱讀理論來(lái)學(xué)習(xí)設(shè)計(jì)模式就有些困難,因?yàn)槟J街惺褂昧瞬煌男g(shù)語(yǔ)。 例如,在這種模式下,我們有subject , 觀察者和client 。 程序員更容易從代碼中理解想法。 因此,我將用代碼描述模式。 示例代碼是用Java編寫(xiě)的,您可以使用任何您喜歡的面向?qū)ο笳Z(yǔ)言。 也許以后我將嘗試使用其他語(yǔ)言代碼鏈接來(lái)編輯文章。
For people who are new to design patterns, please try to write it once yourself, it will do wonders for you.
對(duì)于不熟悉設(shè)計(jì)模式的人,請(qǐng)嘗試自己編寫(xiě)一次,它將為您帶來(lái)奇跡。
主題/發(fā)布者: (Subject / Publisher:)
In observer pattern, the publisher is known as the SUBJECT. The subject maintains a list of observers and notifies them automatically of any state changes. Subject in the Observer pattern has three tasks:
在觀察者模式中,發(fā)布者稱為“ 主題”。 該主題維護(hù)一個(gè)觀察者列表,并自動(dòng)將狀態(tài)變化通知他們。 觀察者模式中的主題具有三個(gè)任務(wù):
i) Provide methods to register and remove observer.
i)提供注冊(cè)和刪除觀察者的方法。
ii) Maintains a list of its observers/subscribers.
ii)維護(hù)其觀察者/訂閱者的列表。
iii) And notify them automatically when any state changes. The Subject broadcasts events to all registered Observers.
iii)并在狀態(tài)發(fā)生變化時(shí)自動(dòng)通知他們。 主題向所有注冊(cè)的觀察員廣播事件。
As it’s going to notify the observer objects about the changes of its state, it is also called the publisher.
由于它將通知觀察者對(duì)象其狀態(tài)的變化,因此也稱為發(fā)布者。
For the implementation, we will define an interface as Subject. Any class that implements this interface is a subject in observer pattern. And the class must define these three functions given in the code below.
對(duì)于實(shí)現(xiàn),我們將 接口 定義 為Subject。 任何實(shí)現(xiàn)此接口的類都是觀察者模式的主題。 并且該類必須定義以下代碼中給出的這三個(gè)函數(shù)。
Subject Interface Code主題界面代碼As you can see from figure 1 users subscribes to a group and gets a notification when a new post is updated. Group class in our example is the subject/publisher. So, it has to implement the Subject interface.
從圖1中可以看到,用戶訂閱了一個(gè)組并在更新新帖子時(shí)收到通知。 在我們的示例中,小組課程是主題 / 發(fā)布者 。 因此,它必須實(shí)現(xiàn)Subject接口。
Figure 2. Class Diagram圖2.類圖In many books and websites, you will see that they put a generalized structure diagram with concreteSubject or concreteObserver. I found it hard as a beginner to relate so many generalized formula. So, we are keeping a class diagram here for better understanding. After completing this implementation, you should go back and check the structure figures in any book or website. It should make much more sense to you, at least that’s what I hope.
在許多書(shū)籍和網(wǎng)站中,您會(huì)看到它們放置了帶有concreteSubject或concreteObserver的通用結(jié)構(gòu)圖。 作為初學(xué)者 ,我發(fā)現(xiàn)很難聯(lián)系這么多廣義公式。 因此,我們?cè)谶@里保留了一個(gè)類圖以便更好地理解。 完成此實(shí)現(xiàn)后,您應(yīng)該返回并檢查任何書(shū)籍或網(wǎng)站中的結(jié)構(gòu)圖。 這對(duì)您來(lái)說(shuō)應(yīng)該更有意義,至少我希望如此。
From the class diagram, you can see Group class implements subject interface. So Group class is now SUBJECT in this example. User class implements observer interface. So User class is OBSERVER. And Group has a list of observer object. So, User can use register and removeobervser methods to be observer of Group class. And Group class can notify observers with update method.
從類圖中,您可以看到Group類實(shí)現(xiàn)主題接口。 因此,在此示例中,Group類現(xiàn)在為SUBJECT。 用戶類實(shí)現(xiàn)觀察者接口。 因此,用戶類是OBSERVER。 并且Group有一個(gè)觀察者對(duì)象列表。 因此,用戶可以使用register和removeobervser方法成為Group類的觀察者。 并且Group類可以使用更新方法通知觀察者。
Now we are into the coding part. Code for Group class is given below. Code link is given at the end of the article.
現(xiàn)在我們進(jìn)入編碼部分。 組類的代碼如下。 本文末尾提供了代碼鏈接。
Group class implements Subject interface組類實(shí)現(xiàn)Subject接口Let’s break it down to understand observer pattern now. Observers can be added and removed from this list and Observer list will keep track of the object list. Here are the two methods provided by Subject class Group for use of observers.
現(xiàn)在讓我們分解以了解觀察者模式。 可以在此列表中添加或刪除觀察者,觀察者列表將跟蹤對(duì)象列表。 這是Subject類Group提供的供觀察者使用的兩種方法。
public void registerObserver(Observer o) {observers.add(o);
}public void removeObserver(Observer o) {
observers.remove(o);
}
For now, let’s examine the last task of our subject, the Group class: notifying the observers. When a new post is posted, notifyObserver method gets the list of all the observers and through the update method sends posts to observer objects.
現(xiàn)在,讓我們檢查主題的最后一個(gè)任務(wù),即Group類:通知觀察者。 發(fā)布新帖子時(shí), notifyObserver方法獲取所有觀察者的列表,并通過(guò)update方法將帖子發(fā)送到觀察者對(duì)象。
public void newPost(String post) {this.post = post;
notifyObserver();
}public void notifyObserver() {
for (Observer observer : observers) {
observer.update(); //update posts for observers
}
}
Now, we can tell that in observer there needs to have an update function. We will discuss about this in next section.
現(xiàn)在,我們可以告訴觀察者需要一個(gè)更新功能。 我們將在下一節(jié)中對(duì)此進(jìn)行討論。
觀察者/訂閱者: (Observer / Subscriber:)
Observer is an actor class in this design pattern, sometimes its confusing as the design pattern name and actor name is the same. As these objects subscribe to the subject they are also known as subscribers. The observers are dependent on the subject. When the subject’s state changes, the observers get notified. In our case, if a new post is there, observers will be notified.
觀察者是此設(shè)計(jì)模式中的一個(gè)actor類,有時(shí)它的混亂之處在于設(shè)計(jì)模式名稱和actor名稱是相同的。 當(dāng)這些對(duì)象訂閱主題時(shí),它們也稱為訂閱者 。 觀察者取決于主題。 當(dāng)對(duì)象的狀態(tài)改變時(shí),觀察者會(huì)收到通知。 在我們的情況下,如果有新職位,將通知觀察員。
Observers subscribe and unsubscribe themselves to the Subject. Normally objects which are observers perform two tasks:
觀察者訂閱和取消訂閱主題。 通常,作為觀察者的對(duì)象執(zhí)行兩項(xiàng)任務(wù):
i) Uses methods provided by the Subject to subscribe and unsubscribe as an observer.
i)使用主題提供的方法以觀察者身份進(jìn)行訂閱和退訂。
ii) Implements Observer interface to get update from Subject.
ii)實(shí)現(xiàn)觀察者接口以從主題獲取更新。
Figure: Relation between observer and subject圖:觀察者與主體之間的關(guān)系Below is the code for Observer interface, which has update function. So the objects who want to get notification of Group update must implement this Observer interface. We will get a look at how other classes use this class and method in User class description. Observer interface has just one function
以下是具有更新功能的Observer界面的代碼。 因此,想要獲取組更新通知的對(duì)象必須實(shí)現(xiàn)此Observer接口。 我們將在User類描述中了解其他類如何使用該類和方法。 觀察者界面只有一項(xiàng)功能
Observer Interface觀察者界面User class implements this Observer interface. So all the objects of user class will be now observers.
用戶類實(shí)現(xiàn)此Observer 接口 。 因此,用戶類的所有對(duì)象現(xiàn)在將成為觀察者 。
User registers as observer using registerObserver method in Subscribe function. And User can be unregistered also from observer list of Group class calling removeObserver method. Group can update new post notification through update function.
用戶使用訂閱功能中的registerObserver方法注冊(cè)為觀察者。 而且,也可以從調(diào)用removeObserver方法的Group類的觀察者列表中注銷(xiāo)User。 群組可以通過(guò)更新 功能來(lái)更新新的帖子通知。
User class becomes observer by implementing Observer interface通過(guò)實(shí)現(xiàn)Observer接口,用戶類成為觀察者客戶/主要功能: (Client/Main function:)
Normally client code in design pattern example is actually code in main function. Its functionality depends on the implementation of the coder. Main function defines the number and type of Observers.
通常,設(shè)計(jì)模式示例中的客戶代碼實(shí)際上是main函數(shù)中的代碼。 其功能取決于編碼器的實(shí)現(xiàn)。 主要功能定義了觀察者的數(shù)量和類型。
Here in client we create a group and take input for some users and those users subscribe to the group. When a new post is entered in the group, all the subscribed users get notification. The last user unsubscribes the group. So, next time a new post does not reach that user.
在客戶端中,我們創(chuàng)建一個(gè)組并為一些用戶輸入內(nèi)容,這些用戶訂閱了該組。 當(dāng)在組中輸入新帖子時(shí),所有訂閱的用戶都會(huì)收到通知。 最后一個(gè)用戶取消訂閱該組。 因此,下一次新帖子無(wú)法到達(dá)該用戶。
Main function is known as the client in design pattern tutorials
設(shè)計(jì)模式教程中的主要功能稱為客戶端
Main function/ Client Code主要功能/客戶代碼樣本輸出: (Sample Output:)
Figure 4: Output of ObserverTest Program圖4:ObserverTest程序的輸出Thank you for your patience. Hope this one gives you a better idea about the observer design pattern. Here is the code link, it’s currently in java. I will try to update the code in other languages also.
感謝您的耐心等待。 希望這能給您關(guān)于觀察者設(shè)計(jì)模式的更好的主意。 這是代碼鏈接 ,它當(dāng)前在java中。 我也將嘗試更新其他語(yǔ)言的代碼。
If you are new to design pattern please don’t copy-paste the code, try to write the code yourself, it will do wonders to your understanding about the pattern. If you need any help or have any tips to improve my writing please let me know.
如果您不熟悉設(shè)計(jì)模式,請(qǐng)不要復(fù)制粘貼代碼, 嘗試自己編寫(xiě)代碼 ,這會(huì)對(duì)您對(duì)模式的理解產(chǎn)生奇妙的效果。 如果您需要任何幫助或有任何技巧來(lái)改善我的寫(xiě)作,請(qǐng)告訴我。
Thank you for reading the article. Have a Good day. 😃
感謝您閱讀這篇文章。 祝你有美好的一天。 😃
Resource: sourcemaking , refactoringGuru, and Head-First Design Pattern book.
資源:Sourcemaking,refactoringGuru和Head-First Design Pattern書(shū)。
翻譯自: https://medium.com/dev-genius/observer-pattern-explanation-a-trial-of-blending-theory-with-practical-d68c8a482f38
設(shè)計(jì)模式觀察者模式
總結(jié)
以上是生活随笔為你收集整理的设计模式观察者模式_观察者设计模式教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 频谱分析仪原理结构框图
- 下一篇: MySQL系统流程图怎么画_Word流程