#include <iostream> using namespace std; class Singleton { public: static Singleton *getInstance() { if (_ins == nullptr) _ins = new Singleton; return _ins; } private: static Singleton * _ins; Singleton(){} Singleton(const Singleton &){} Singleton operator=(const Singleton &){} ~Singleton(){} }; Singleton *Singleton::_ins = nullptr; int main(int argc, char *argv[]) { Singleton *p1 = Singleton::getInstance(); Singleton *p2 = Singleton::getInstance(); if (p1 == p2) { cout << "p1==p2" << endl; } return 0; }
A,B,C均要配置文件,xx.conf 不想使用全局变量 怎么办?->单例
//单例是共享数据,取代全局
config.h #ifndef CONFIG_H #define CONFIG_H #include <iostream> #include <string> using namespace std; struct info { string ip; string port; }; class Config { public: static Config *getInstance(); string getIp(); string getPort(); private: static Config *_ins; info _inf; Config(); ~Config(); }; #endif // CONFIG_H
config.cpp #include "config.h" #include <fstream> Config *Config::_ins = nullptr; Config *Config::getInstance() { if (_ins == nullptr) _ins = new Config; return _ins; } Config::Config() { fstream fs; fs.open("/home/zzz/Workspace/pattern/Singleton/untitled/com.conf", ios::in|ios::out); if (!fs) { cout << "open error!"; } fs >> _inf.ip; fs >>_inf.port; fs.close(); } string Config::getIp() { return _inf.ip; } string Config::getPort() { return _inf.port; }
a.h #ifndef A_H #define A_H class A { public: A(); }; #endif
a.cpp #include "a.h" #include "config.h" A::A() { Config *conf = Config::getInstance(); cout << "ip:" << conf->getIp() << endl; cout << "port:" << conf->getPort() << endl; }
b.h #ifndef B_H #define B_H class B { public: B(); }; #endif // B_H
b.cpp #include "b.h" #include "config.h" B::B() { Config *conf = Config::getInstance(); cout << "ip:" << conf->getIp() << endl; cout << "port:" << conf->getPort() << endl; }
c.h #ifndef C_H #define C_H class C { public: C(); }; #endif // C_H
c.cpp #include "c.h" #include "config.h" C::C() { Config *conf = Config::getInstance(); cout << "ip:" << conf->getIp() << endl; cout << "port:" << conf->getPort() << endl; }