單例模式

單例模式

單例模式使咱們使用很是多的模式,也是很簡單的一個設計模式。ios

模式原理

單例模式經過私有化類的構造函數來避免外部建立該類的實例,僅僅提供一個靜態的getInstace()方法來獲取在類內部建立的一個全局惟一的實例,同時在該方法種建立惟一實例,還要保證建立過程是線程安全的。c++

使用場景

單例模式的使用場景能夠從他的特性來分析,好比:windows

  1. windows的畫圖工具,畫筆是單例,可是畫布是咱們能夠隨意建立的。咱們能夠改變畫筆的顏色和粗細,可是咱們用來畫出圖案的畫筆實例永遠是同一個;
  2. 也能夠把一些通用的方法放到一個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.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;
}
相關文章
相關標籤/搜索