單例模式
單例模式使我們使用非常多的模式,也是很簡單的一個設計模式。
模式原理
單例模式通過私有化類的構造函數來避免外部創建該類的實例,僅僅提供一個靜態的getInstace()方法來獲取在類內部創建的一個全局唯一的實例,同時在該方法種創建唯一實例,還要保證創建過程是線程安全的。
使用場景
單例模式的使用場景可以從他的特性來分析,比如:
- windows的畫圖工具,畫筆是單例,但是畫布是我們可以隨意創建的。我們可以改變畫筆的顏色和粗細,但是我們用來畫出圖案的畫筆實例永遠是同一個;
- 也可以把一些通用的方法放到一個commonn類里面定義成static的方法,這樣我們就可以通過common的單例來調用這些方法,當然簡單的使用全局函數也是可以滴~。這里的單例就更多的是貢獻了它的封裝特性;
代碼實現
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.cpp
#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.cpp
#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;
}