C++ 单例模式(singleton)

static实现

单例模式是设计模式中最简单的设计模式,也是做容易实现的模式。所谓单例模式就是让某个类只能产生一个对象。那么在C++语言中该如何设计呢?用static关键字可以实现单例模式,因为static保证同时只有一个对象的产生。下面是单例模式的代码的static实现方式:

class single_printer {
     
public:
    void print(const string& str);
    static void test() {
     
        cout<<"hello"<<endl;
    }
    
    static single_printer& get_printer();

  //禁止拷贝
  single_printer(const single_printer&) = delete;
  single_printer& operator=(const single_printer&) = delete;

private:
    single_printer() {
     };
};

single_printer& single_printer::get_printer() {
     
    static single_printer single;
    return single;
}
void single_printer::print(const string& str) {
     
    cout << str << endl;
}

上述代码通过delete禁止拷贝,然后将构造函数声名为private,这样就使得非成员函数没法构造该类的对象,而get_printer为成员函数,因此可以调用private的成员函数,而返回的是一个static对象,这就保证了该类只有一份实体对象。而将器封装于函数内部的好处是,当调用该函数才会产生实体对象,如果不调用该函数则不会产生一份实体对象。
那么对于该对象的调用方式应该是这样的:

single_printer::get_printer().print("hello");

计数器实现

除了上述的方法外,也可以用计数器的方式来实现单例模式,计数器的实现参照如下方式:

//采用计数方式实现的单例模式
class printer {
     
public:
    static printer* get_printer();
    ~printer();
    void print(const string& str);
	 //禁止拷贝
    printer(const printer&) = delete;
    printer & operator=(const printer&) = delete;

private:
    static size_t obj_numbers;
    printer();
};

//静态成员函数类外定义
size_t printer::obj_numbers = 0;

printer::printer() {
     }

printer::~printer() {
     
    obj_numbers--;
}
printer* printer::get_printer() {
     
    if (obj_numbers == 1) return nullptr;
    obj_numbers++;
    return new printer;
    
};
void printer::print(const string& str) {
     
    cout << str << endl;
}

int main()
{
        
    single_printer::get_printer().print("hello");
    printer * single_p = printer::get_printer();
    printer  * more_than_one = printer::get_printer();
    if (more_than_one == nullptr) {
     
        cout << "只能有一个" << endl;
    }
    delete single_p;
    more_than_one = printer::get_printer();
    if (more_than_one == nullptr) {
     
        cout << "现在可以了?" << endl;
    }
    else {
     
        more_than_one->print("可以创建了");
    }
    delete more_than_one;
}

当以已经有一个对象时,我们我们继续尝试获取对象则会得到一个空指针,因此,无论什么情况下都只能产生一个对象。

代码参考《More Effective c++》

你可能感兴趣的:(设计模式,设计模式,c++)