2. 多态回调 (观察者模式) 性能:相较全局函数,略差。因为都来虚函数表和虚函数指针转换操作。 / enum Event { EVENT_ATMOSPHERE_CHANGE = 0 }; / class Listener { public: virtual void country_call_back(Event e) = 0; }; class Country : public Listener { public: virtual void country_call_back(Event e) { printf("country->earthquake /n"); } }; / class Butterfly : private std::vector<Listener*> { public: typedef std::vector<Listener*> base; using base::begin; using base::end; using base::push_back; using base::erase; using base::iterator; public: void butterfly_fiap_wings() { printf("butterfly fiap wings /n"); Event e; e = EVENT_ATMOSPHERE_CHANGE; for(iterator i=begin(); i!=end(); ++i) (*i)->country_call_back(e); } void add_listener(Listener *listener) { push_back(listener); } void remove_listener(Listener *listener) { erase(std::remove(begin(), end(), listener), end()); } }; / int main(int argc, char* argv[]) { Country *country = new Country; Butterfly *butterfly = new Butterfly; butterfly->add_listener(country); butterfly->butterfly_fiap_wings(); return 0; } 待续......