Suppose there is a software company that notifies some customers of the information whenever a new product is launched.
Abstract The notification action into an interface.
Public interface IService
{
Void Notif ();
}
If you want to receive notifications, you need to implement the above interfaces. The customer here is seen as the Observer.
Public class CustomerA: IService
{
Public void Notif ()
{
Console. WriteLine ("customer A has received A notification ~~ ");
}
}
Public class CustomerB: IService
{
Public void Notif ()
{
Console. WriteLine ("Customer B has received a notification ~~ ");
}
}
As a software company, it maintains a collection of customers and provides methods for registering and canceling registration to add or delete customers to the collection. Whenever there is a notification, we traverse the customer set and let IService execute the notification. A software company can be seen as an observed object, or as the source of initiating an action.
Public class MyCompany
{
Private IList <IService> subscribers = new List <IService> ();
Public void Subscribe (IService subscriber)
{
Subscribers. Add (subscriber );
}
Public void CancelSubscribe (IService subscriber)
{
Subscribers. Remove (subscriber );
}
Public void SendMsg ()
{
Foreach (IService service in subscribers)
{
Service. Notif ();
}
}
}
The client creates software company instances, creates observer instances, registers or cancels observers, and so on.
Class Program
{
Static void Main (string [] args)
{
MyCompany company = new MyCompany ();
IService customerA = new CustomerA ();
IService customerB = new CustomerB ();
Company. Subscribe (customerA );
Company. Subscribe (customerB );
Company. SendMsg ();
Console. ReadKey ();
}
}
Summary:
● Abstract the action of a notification into an interface
● If the observer wants to receive the notification, the notification interface is implemented.
● The observed object performs three tasks: maintaining the set of observers, registering/canceling the observer, and initiating an action to traverse the Observer set so that the notification interface can do the same thing.
Observer Mode