简体   繁体   中英

Observer pattern, smart pointers and singleton classes

I want to create an Obserer pattern using smart pointers. This is my class:

class Observable {
public:
    void addObserver(std::shared_ptr<Observer> ptr);
private:
    std::list<std::weak_ptr<Observer>> observers;
};

The use of smart pointers provides strong guarantees about memory leak, however I don't understand how to manage list of observers when I don't have a shared_ptr . Example for singleton classes:

class Singleton {
private:
  Singleton();
public:
  static Singleton& getInstance() {
      static Singleton instance;
      return instance;
  }
}

In this case I don't have a shared ptr but the singleton class can be an observer. Does it mean that I need to return a shared_ptr from a singleton class? Is there any design detail to take into account?

I used a different strategy:

class ObserverWrapper: public Observer {
public:
  void notify() override {
      ref.notify();
  }
private:
  Observer& ref;
};

class ObserverProxy: public Observer {
public:
    operator std::shared_ptr<Observer>() {
       return wrapper;
    }
    ObserverProxy() : wrapper(std::make_shared<Observer>(*this) {
    }
private:
    std::shared_ptr<Observer> wrapper;
};

class Singleton: public ObserverProxy {
public:
  void notify() override {
      //something here
  }
};

Now I can do:

Singleton& s = Singleton::getInstance();
Observable obs;
obs.addObserver(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM