Suppose there is a software company that notifies a number of customers whenever a new product is introduced.
Abstract the notification action as an interface.
public interface IService
{
void Notif ();
}
Customers need to implement the above interfaces if they want to be notified. The clients here are seen as observers.
public class Customera:iservice
{
public void Notif ()
{
Console.WriteLine ("Customer A has received the notice ~ ~");
}
}
public class Customerb:iservice
{
public void Notif ()
{
Console.WriteLine ("Customer B received the notice ~ ~");
}
}
As a software company, it maintains a collection of customers and provides a way to register, unregister, and add or remove customers to this collection. Whenever there is a notification, iterate through the customer collection and let IService execute the notification. A software company can be seen as an object of observation, or a source of initiating 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 a software company instance, creates an observer instance, registers or cancels the observer, 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 ();
}
}
Summarize:
Abstract the action of a notification into an interface
Observers implement notification interfaces if they want to receive notifications
3 Things to be observed: maintain a collection of observers, register/Cancel observers, initiate an action traversal observer collection let the notification interface do things
C#_ Observer pattern