單例模式使咱們使用很是多的模式,也是很簡單的一個設計模式。ios
單例模式經過私有化類的構造函數來避免外部建立該類的實例,僅僅提供一個靜態的getInstace()方法來獲取在類內部建立的一個全局惟一的實例,同時在該方法種建立惟一實例,還要保證建立過程是線程安全的。c++
單例模式的使用場景能夠從他的特性來分析,好比:windows
draw.h設計模式
#include <string> #include "singleton.h" class Draw { public: void show(); Draw(std::string name); void setPan(); private: std::string m_Name; };
draw.cpp安全
#include <iostream> #include "draw.h" Draw::Draw(std::string name) :m_Name(name) { } void Draw::show() { std::cout << m_Name << ":" << std::endl; for(int n = 0; n < 20; ++n) { for(int m = 0; m < n; ++m) { // std::cout << "*"; std::cout << Pen::getInstance()->draw(); } std::cout << std::endl; } }
properties.h函數
#include <string> struct ProPerties { std::string p_Color; uint32_t p_Width; std::string p_Shape; };
singleton.h工具
#include "properties.h" class Pen { public: static Pen* getInstance(); void setProperty(const ProPerties& proty); std::string draw(); private: Pen(); ProPerties m_Property; };
singleton.cppui
#include "singleton.h" Pen *Pen::getInstance() { //線程安全 static Pen sig; return &sig; } void Pen::setProperty(const ProPerties &proty) { m_Property = proty; } std::string Pen::draw() { return m_Property.p_Shape; } Pen::Pen() { }
main.cppspa
#include <iostream> #include <thread> #include "singleton.h" #include "properties.h" #include "draw.h" using namespace std; int main() { Pen* sig = Pen::getInstance(); ProPerties proty; proty.p_Color = "red"; proty.p_Width = 65; proty.p_Shape = '*'; sig->setProperty(proty); std::thread t1([](){ Draw d1("Draw1"); d1.show(); }); std::thread t2([](){ Draw d2("Draw2"); d2.show(); }); std::thread t3([](){ Draw d3("Draw3"); d3.show(); }); t1.join(); t2.join(); t3.join(); return 0; }