This article briefly describes the C# observer model in an example form and shares it with you for your reference. The specific implementation method is as follows:
Now suppose there is a software company that will notify some customers of the information whenever a new product is launched.
Abstract the notification action into an interface. The code looks like this:
public interface IService { void Notif(); }
If a customer wants to get notification, he needs to implement the above interface. The customers here are seen as observers.
public class CustomerA : IService { public void Notif() { ("Customer A has received the notification~~"); } } public class CustomerB : IService { public void Notif() { ("Customer B received the notification~~"); } }
As a software company, it maintains a collection of customers and provides methods to register and cancel registration, adding or deleting customers to this collection. Whenever there is a notification, it traverses the client collection and lets the IService execute the notification. A software company can be regarded as an object to be observed, or the source of the action.
public class MyCompany { private IList<IService> subscribers = new List<IService>(); public void Subscribe(IService subscriber) { (subscriber); } public void CancelSubscribe(IService subscriber) { (subscriber); } public void SendMsg() { foreach (IService service in subscribers) { (); } } }
The client creates software company instances, creates observer instances, registers or cancels observers, etc.
class Program { static void Main(string[] args) { MyCompany company = new MyCompany(); IService customerA = new CustomerA(); IService customerB = new CustomerB(); (customerA); (customerB); (); (); } }
Summarize:
①Abstract the action of a notification into an interface
② If an observer wants to receive notifications, he/she implements the notification interface.
③ The object being observed does 3 things: maintain the set of observers, register/cancel the observer, initiate an action to traverse the set of observers, and let the notification interface do things
I hope this article will be helpful to everyone's C# programming learning.