This is the 15th day of my participation in the August More Text Challenge

Observer Pattern is one of the behavior patterns in design patterns, which solves the reuse problem of objects with one-to-many dependencies. Participants in this model are divided into two categories: the target being observed and the observers observing the target.

Because this pattern is based on a one-to-many relationship, it is typically applied to situations consisting of a single target object and N observer objects (of course, it can be extended to multiple target objects, but we will only discuss the former for now).

When the state of the target object changes or makes a certain behavior, the observers who are observing the target object will automatically and chain the corresponding response behavior.

The role abstraction Subject in the pattern: It stores references to all observer objects in an aggregate, and each topic can have any number of observers. Abstract topics provide an interface to add and remove observer objects. ConcreteSubject: Store the state in a concrete observer object; All registered observers are notified when the internal status of a specific topic changes. Abstract Observers: Define an interface for all concrete observers to update themselves when notified of a topic. ConcreteObserver: Implements the update interface required by the abstract observer role to harmonize its own state with the topic state.

Observer pattern class diagram:

Here’s an example:

Csdn blog is an observer model. For example, if you follow some author’s blog, when the author has a blog to publish, you will receive a message from that author’s blog.

Abstract Topic: Blog Blog

Specific topic: MyBlog’s blog

Abstract observer: IObserver

Observer = Observer

The code:

First we need to define an abstract class for the blog with subscription functionality

Blog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Observer
{
    /// <summary>
    ///Blog abstract class with subscription functionality
    /// </summary>
    public abstract class blog
    {
        /// <summary>
        ///List of subscribers
        /// </summary>
        public List<IObserver> observerList = new List<IObserver>();
        /// <summary>
        ///Blog title
        /// </summary>
        public string blogTitle = "";
        /// <summary>
        ///bloggers
        /// </summary>
        public string blogAuthor = "";
        /// <summary>
        ///The constructor
        /// </summary>
        /// <param name="title">Blog title</param>
        /// <param name="author">bloggers</param>
        public blog(string title,string author)
        {
            this.blogAuthor = author;
            this.blogTitle = title;
        }
  
        /// <summary>
        ///Add subscribers
        /// </summary>
        /// <param name="name">Subscriber object</param>
        public void AddObserver(IObserver name)
        {
            // If it is not subscribed, add it
            if (!observerList.Contains(name))
            {
                observerList.Add(name);
            }
        }
  
        /// <summary>
        ///Delete the subscriber
        /// </summary>
        /// <param name="name">Subscriber object</param>
        public void DelObserver(IObserver name)
        {
            // If it is not subscribed, add it
            if (!observerList.Contains(name))
            {
                observerList.Remove(name);
            }
        }
  
        /// <summary>
        ///Send a message
        /// </summary>
        public void SendMessage()
        {
            for (int i = 0; i < observerList.Count; i++)
            {
                observerList[i].AcceptMessage(this); }}}}Copy the code

Next we need an observer interface:

IObserver.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Observer
{
    /// <summary>
    ///Subscriber interface
    /// </summary>
    public interface IObserver
    {
        void AcceptMessage(blog blogs); }}Copy the code

Specific blogs

MyBlog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Observer
{
    public class MyBlog : blog
    {
        public MyBlog(string title,string author) : base(title,author){}}}Copy the code

Specific observer:

Observer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Observer
{
    public class Observer:IObserver
    {
        /// <summary>
        ///Subscriber name
        /// </summary>
        public string observerName = "";
  
        public Observer(string name)
        {
            this.observerName = name;
        }
  
        /// <summary>
        ///Accept the blog notification method
        /// </summary>
        /// <param name="blogs"></param>
        public void AcceptMessage(blog blogs)
        {
            Console.WriteLine("Subscriber"+observerName+"Yes."+blogs.blogAuthor+"Published"+blogs.blogTitle+"Notice of"); }}}Copy the code

Client call:

ProGram.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace Observer
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize three subscribers
            Observer aaa = new Observer("Zhang");
            Observer bbb = new Observer("Bill");
            Observer ccc = new Observer("Fifty");
  
            // Initialize a blog
            MyBlog gc = new MyBlog("Observer model"."camellia");
            // Add three subscribers to the blog
            gc.AddObserver(aaa);
            gc.AddObserver(bbb);
            gc.AddObserver(ccc);
            // Send blog notificationsgc.SendMessage(); Console.ReadKey(); }}}Copy the code

The final effect is as follows:

The observer pattern is primarily used for one-to-many dependencies, allowing multiple observer objects to listen on a subject object that notifies all observers of changes in state. The observer pattern should be considered when one object needs to change at the same time as other objects, and it is not known how many objects need to be changed.

So that’s the general implementation of the observer.

C# also has an example of using delegates to implement the observer pattern. The difference is that the subscriber interface is replaced by a delegate. The rest is the same, here is not to show, and interest can try.

For good suggestions, please enter your comments below. Welcome to my blog guanchao.site

Welcome to applets: