首页 > 编程语言 >设计模式<c++> (3)观察者模式

设计模式<c++> (3)观察者模式

时间:2023-12-24 20:12:49浏览次数:46  
标签:std Observer void 观察者 模式 virtual message 设计模式 subject

 

/**
 * Observer Design Pattern
 *
 * Intent: Lets you define a subscription mechanism to notify multiple objects
 * about any events that happen to the object they're observing.
 *
 * Note that there's a lot of different terms with similar meaning associated
 * with this pattern. Just remember that the Subject is also called the
 * Publisher and the Observer is often called the Subscriber and vice versa.
 * Also the verbs "observe", "listen" or "track" usually mean the same thing.
 */

#include <iostream>
#include <list>
#include <string>

class IObserver {
public:
    virtual ~IObserver() {};
    virtual void Update(const std::string& message_from_subject) = 0;
};

class ISubject {
public:
    virtual ~ISubject() {};
    virtual void Attach(IObserver* observer) = 0;
    virtual void Detach(IObserver* observer) = 0;
    virtual void Notify() = 0;
};

/**
 * The Subject owns some important state and notifies observers when the state
 * changes.
 */

class Subject : public ISubject {
public:
    virtual ~Subject() {
        std::cout << "Goodbye, I was the Subject.\n";
    }

    /**
     * The subscription management methods.
     */
    void Attach(IObserver* observer) override {
        list_observer_.push_back(observer);
    }
    void Detach(IObserver* observer) override {
        list_observer_.remove(observer);
    }
    void Notify() override {
        std::list<IObserver*>::iterator iterator = list_observer_.begin();
        HowManyObserver();
        while (iterator != list_observer_.end()) {
            (*iterator)->Update(message_);
            ++iterator;
        }
    }

    void CreateMessage(std::string message = "Empty") {
        this->message_ = message;
        Notify();
    }
    void HowManyObserver() {
        std::cout << "There are " << list_observer_.size() << " observers in the list.\n";
    }

    /**
     * Usually, the subscription logic is only a fraction of what a Subject can
     * really do. Subjects commonly hold some important business logic, that
     * triggers a notification method whenever something important is about to
     * happen (or after it).
     */
    void SomeBusinessLogic() {
        this->message_ = "change message message";
        Notify();
        std::cout << "I'm about to do some thing important\n";
    }

private:
    std::list<IObserver*> list_observer_;
    std::string message_;
};

class Observer : public IObserver {
public:
    Observer(Subject& subject) : subject_(subject) {
        this->subject_.Attach(this);
        std::cout << "Hi, I'm the Observer \"" << ++Observer::static_number_ << "\".\n";
        this->number_ = Observer::static_number_;
    }
    virtual ~Observer() {
        std::cout << "Goodbye, I was the Observer \"" << this->number_ << "\".\n";
    }

    void Update(const std::string& message_from_subject) override {
        message_from_subject_ = message_from_subject;
        PrintInfo();
    }
    void RemoveMeFromTheList() {
        subject_.Detach(this);
        std::cout << "Observer \"" << number_ << "\" removed from the list.\n";
    }
    void PrintInfo() {
        std::cout << "Observer \"" << this->number_ << "\": a new message is available --> " << this->message_from_subject_ << "\n";
    }

private:
    std::string message_from_subject_;
    Subject& subject_;
    static int static_number_;
    int number_;
};

int Observer::static_number_ = 0;

void ClientCode() {
    Subject* subject = new Subject;
    Observer* observer1 = new Observer(*subject);
    Observer* observer2 = new Observer(*subject);
    Observer* observer3 = new Observer(*subject);
    Observer* observer4;
    Observer* observer5;

    subject->CreateMessage("Hello World! :D");
    observer3->RemoveMeFromTheList();

    subject->CreateMessage("The weather is hot today! :p");
    observer4 = new Observer(*subject);

    observer2->RemoveMeFromTheList();
    observer5 = new Observer(*subject);

    subject->CreateMessage("My new car is great! ;)");
    observer5->RemoveMeFromTheList();

    observer4->RemoveMeFromTheList();
    observer1->RemoveMeFromTheList();

    delete observer5;
    delete observer4;
    delete observer3;
    delete observer2;
    delete observer1;
    delete subject;
}

int main() {
    ClientCode();
    return 0;
}

 

标签:std,Observer,void,观察者,模式,virtual,message,设计模式,subject
From: https://www.cnblogs.com/airduce/p/17924783.html

相关文章

  • 设计模式<c++> (2)单例模式
    #include<iostream>#include<thread>#include<mutex>classSingleton{private:staticSingleton*pinstance_;staticstd::mutexmutex_;protected:Singleton(conststd::stringvalue):value_(value){}~Single......
  • 观察者模式揭秘:实现松耦合的事件通知机制
    推荐语本篇文章深度剖析了观察者模式的核心原理及其在软件开发中的重要应用,通过清晰而深入的讲解,读者小伙伴可以深入理解观察者模式如何实现松耦合的事件通知机制,从而构建更灵活、可扩展的软件系统。本文既适合希望深入了解设计模式的专业人士,也适合希望提升代码质量和可维护性的开......
  • Java涉及模式有几种,以及什么时候使用
    Java涉及的设计模式一共有23种,按照功能分为三类:创建型模式:包括工厂模式、抽象工厂模式、单例模式、建造者模式和原型模式。当需要对对象的创建进行更好的抽象和封装时,可以考虑使用创建型模式。比如,当系统中的对象创建过程较为复杂,希望封装这些复杂的创建过程,或者需要对对象的创......
  • 提高代码复用性与可维护性:深入剖析模板方法模式
    什么是模板方法模式模板方法模式是一种行为型设计模式,它定义了一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。在模板方法模式中,抽象类负责给出算法的轮廓和骨架(由一个或多个模板方法组成),而实现类......
  • 策略模式(Strategy Pattern) .Net Core实现
    在策略模式(StrategyPattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象。策略对象改变context对象的执行算法。意图:定义一系列的算法,把它们一个个......
  • 设计模式<c++> (1)策略模式
    一、定义策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。二、使用场景客户需要很多种鸭子。要求:1.每种鸭子都要会游泳。2.每种鸭子有叫和飞的行为。3.鸭子的叫和飞的行为可以在使用......
  • 设计模式之单例模式
    单例模式(单例模式)定义==单例模式==确保一个类只有一个实例,并提供一个全局访问点。单例模式实现的方式1.饿汉式publicclassHungry{//构造器私有privateHungry(){}//类加载时就初始化,主动创建privatestaticHungryhungry=newHungry();......
  • 设计模式—工厂模式
    介绍代码接口创建Shape接口publicinterfaceShape{voiddraw();}实现类创建Shape接口的三个实现类:Cirle、Rectangle、SquarepublicclassCircleimplementsShape{@Overridepublicvoiddraw(){System.out.println("Circle");}}......
  • 26.基于 page object 模式的测试框架优化实战
    目录异常处理(弹窗黑名单)日志记录报告生成测试数据的数据驱动异常弹框处理定义黑名单列表处理弹框#声明一个黑名单defblack_wrapper(fun):defrun(*args,**kwargs):basepage=args[0]try:returnfun(*args,**kwargs)......
  • 设计模式—适配器模式
    介绍代码接口定义媒体播放器接口MediaPlayer,其中play方法用于播放媒体文件publicinterfaceMediaPlayer{publicvoidplay(StringaudioType,StringfileName);}定义高级播放器接口AdvancedMediaPlayer,规定指定类型媒体的播放方法publicinterfaceAdvancedMe......