"Learn Swift from Scratch" study notes (Day 66) - Cocoa Touch design mode and application notification mechanism

Original article, welcome to reprint. Please indicate: Guan Dongsheng's blog 

The notification ( Notification ) mechanism is based on the Observer ( Observer ) pattern, also known as the Publish / Subscribe ( Publish/Subscribe ) pattern, which is an important part of the MVC ( Model - View - Controller) pattern.  

Questions raised 

Weather has always been a topic that British people like to discuss, and in recent years, weather changes have also become a topic of great concern to Chinese people. I will decide whether to take the subway or drive to work based on the weather forecast, and my daughter will also decide what clothes to wear tomorrow based on the weather forecast. So I customized the weather forecast SMS notification service for my mobile phone in the mobile company, and its working model is shown in the figure.

 

 

 



  

 

Every day, the Bureau of Meteorology sends the weather forecast information to the mobile operator, and the SMS center of the mobile operator is responsible for sending the weather forecast to the mobile phones that have customized this service. 

In a software system, a change in the state of one object will also affect the state of many other objects. There are many design solutions that can achieve this requirement , but the observer pattern is the most suitable one that can achieve strong reusability and anonymous communication between objects.  

solution 

The notification mechanism can implement "one-to-many" communication between objects. As shown, all objects in the notification mechanism that are interested in a notification can be recipients. First, these objects need to send an addObserver message to the notification center ( NSNotificationCenter ) for registration notification. After the delivery object sends the notification to the notification center through the postNotificationName message, the notification center will broadcast the notification to the registered recipients. All recipients do not know who sent the notification, let alone its details. There is a one-to-many relationship between the sender and the receiver. If the receiver no longer pays attention to the notification, it will send a removeObserver message to the notification center to cancel the notification, and will no longer receive the notification in the future.

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042602&siteId=291194637