当前位置:网站首页>Example of observer mode of C -- ordering milk
Example of observer mode of C -- ordering milk
2022-07-28 18:48:00 【Chen Yan will act】
One , Introduction to observer mode
1.1 Observer mode definition
Intention : Defines a one-to-many dependency between objects , When the state of an object changes , All objects that depend on it can be notified and updated automatically .
Applicability :
- When the state of one object changes, other objects need to be changed , Or when the actual object is unknown or dynamically changing in advance , You can use observer mode .
- When some objects in the application observe other objects , You can use this pattern . Subscription lists are dynamic , Therefore, subscribers can join or leave this list at any time .
1.2 Observer pattern structure
Publisher : Will send interesting events to other objects . Events occur after the publisher's own state changes or performs a specific behavior . The publisher contains a subscription framework that allows new subscribers to join and current subscribers to leave the list .
When something new happens , The sender will traverse the subscription list and call the notification method of each subscriber object . The method is declared in the subscriber interface .
subscriber : The interface declares the notification interface . In the vast majority of cases , The interface contains only one update Update method . The method can have multiple parameters , Enable publishers to pass event details when updating .
Specific subscribers : You can do something to respond to a publisher's notification . All concrete subscriber classes implement the same interface , Therefore, publishers do not need to be coupled to specific classes .
Subscribers often need some context information to properly handle updates . therefore , Publishers usually pass some context data as parameters of notification methods . Publishers can also pass themselves as parameters , Enable subscribers to directly obtain the required data .
client : The publisher and subscriber objects are created separately , Then register publisher updates for subscribers .
Two , Example of ordering milk
2.1 Problem description
If you subscribe to a milk , Then there is no need to go to the dairy to buy milk . Milk station ( That is... In application “ Publisher ”) After the milk arrives ( Even ahead of time ) Send the milk directly to your home .
The milk station is responsible for maintaining the subscriber list , Find out what kind of milk subscribers are interested in . When subscribers want to stop subscribing to milk , They can withdraw from this list at any time .
2.2 Realize the idea
- Declare the subscriber interface . This interface declares a notification method .
- Declare the publisher interface and define some interfaces to add and delete subscription objects in the list .
- Create a specific publisher class . Every time a publisher has an important event, all subscribers must be notified .
- Implement the method of notification update in the specific subscriber class .
2.3 The sample code
using System;
using System.Collections.Generic;
namespace MilkDemo
{
// Observer interface
public interface IObserver
{
// Observer properties --> Names and things like that
string Name {
get; set; }
// Observer method --> Receive notice ( Called )
void ReceiveMilk(IMilkStation subject);
}
// subscribers A
class ObserverUserA : IObserver
{
public string Name
{
get; set;
}
public ObserverUserA(string name)
{
this.Name = name;
}
public void ReceiveMilk(IMilkStation subject)
{
Console.WriteLine(this.Name + ": I got it. , Subscribed milk ");
Console.WriteLine(this.Name + " Take a look at the quantity of remaining milk in the remaining milk station :" + subject.MilkCount);
}
}
// subscribers
class ObserverUserB : IObserver
{
public string Name
{
get; set;
}
public ObserverUserB(string name)
{
this.Name = name;
}
public void ReceiveMilk(IMilkStation subject)
{
Console.WriteLine(this.Name + ": I got it. , Subscribed milk ");
}
}
// Milk station interface
public interface IMilkStation
{
int MilkCount {
get; set; }
// Order milk --> Add you to the milk delivery list ( Push notification )--> Attach the observer to the subject
void Attach(IObserver observer);
// Unsubscribe milk --> Remove from the remove delivery milk list --> Remove the observer from the subject
void Detach(IObserver observer);
// Deliver milk --> Notify observer
void Distribution();
}
/// <summary>
/// Milk delivery clerk
/// Deliver milk according to the milk list ordered by the milk station --> Notify observer
/// </summary>
public class MilkCourier : IMilkStation
{
// The amount of milk left in the milk station
public int MilkCount {
get; set; }
// All customers who order milk --> Observers who need to be informed
private List<IObserver> observerList = new List<IObserver>();
public MilkCourier(int milkCount)
{
this.MilkCount = milkCount;
}
// How to order milk -- Add observer implementation
public void Attach(IObserver observer)
{
Console.WriteLine(" Milk station : Received a customer ordering milk ");
this.observerList.Add(observer);
}
// Unsubscribe method --> Remove the observer implementation
public void Detach(IObserver observer)
{
this.observerList.Remove(observer);
Console.WriteLine(" Milk station : Received a user unsubscribe ");
}
// Trigger updates in each subscriber .
public void Distribution()
{
Console.WriteLine(" Milk station : Milk delivery ...");
foreach (var observer in observerList)
{
observer.ReceiveMilk(this);
}
}
public void SomeLogical()
{
if (MilkCount > observerList.Count)
{
Console.WriteLine(" The amount of milk left in the milk station : " + this.MilkCount);
this.MilkCount -= observerList.Count;
this.Distribution();
Console.WriteLine(" The remaining quantity after this delivery : " + this.MilkCount);
}
else
{
Console.WriteLine(" The amount of milk left in the milk station : " + this.MilkCount + ", Not enough to deliver all subscribers ;");
}
}
}
class Program
{
static void Main(string[] args)
{
// Initialize the milk station
MilkCourier milkCourier = new MilkCourier(10);
// Initialize user A,B And order milk
IObserver observerA = new ObserverUserA(" Chen will do what he says ");
milkCourier.Attach(observerA);
IObserver observerB = new ObserverUserB("Czhenya");
milkCourier.Attach(observerB);
// Milk station delivery
milkCourier.SomeLogical();
Console.WriteLine();
Console.WriteLine("-------- After a period of simulation ----------");
Console.WriteLine();
// user B unsubscribe
milkCourier.Detach(observerB);
// Milk station delivery
milkCourier.SomeLogical();
Console.Read();
}
}
}
Running results :
边栏推荐
- LeetCode_63_不同路径Ⅱ
- insight! Baidu pushed redis ceiling notes, which was originally understood by the database
- Ue5 gas learning notes 1.5 gameplay effects game effects
- C# 之 观察者模式实例 -- 订牛奶
- How to see the future development of software testing?
- MongoDB数据库shell命令执行
- EasyNLP中文文图生成模型带你秒变艺术家
- Ue5 gas learning notes 1.8 game special effects (gameplaycue)
- Zen project management software is an indispensable tool for agile development teams
- LeetCode_ 63_ Different paths II
猜你喜欢

MYSQL入门与进阶(五)

1.3、链表

三分钟了解快来新媒体

Wired: who owns the art of the future? Openai allows dall-e users to commercialize their works. At present

APP为什么用JSON协议与服务端交互:序列化相关知识

Mqtt over quic: the next generation Internet of things standard protocol injects new impetus into the message transmission scenario

It is said that software testing is the worst in the IT industry. Is that so?

ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法

Introduction and advanced level of MySQL (5)

redis优势以及数据结构相关知识
随机推荐
UE5 GAS 学习笔记 1.4属性集
What is the employment prospect of software testing?
Golang 打包发布到各个平台
MYSQL入门与进阶(六)
数字经济时代的开源数据库创新 | 2022开放原子全球开源峰会数据库分论坛圆满召开
One Hot编码是什么?为什么要用它,什么时候用它?
GO exe生成图标版本信息
专题讲座6 树形dp 学习心得(长期更新)
记录自己在厦门两年来的面试经历--完结篇
MYSQL入门与进阶(五)
LeetCode_ 96_ Different binary search trees
EasyCVR新版本级联时,下级平台向上传递层级目录显示不全的原因分析
NDK series (5): from introduction to practice, JNI explodes the liver and explains everything in detail!
先验、后验、似然
LeetCode_63_不同路径Ⅱ
当Golang遇到高并发秒杀
EasyNLP中文文图生成模型带你秒变艺术家
Zero knowledge proof: zkp with DDH assumption
haproxy实现灰度发布
LeetCode_ 1137_ Nth teponacci number