4

静态成员实现单例模式

 2 years ago
source link: https://segmentfault.com/a/1190000041206228
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

静态成员实现单例模式

发布于 今天 13:58

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

Singleton(单例):在单例类的内部实现只生成一个实例,同时它提供一个静态getInstance()工厂方法,让客户可以访问它的唯一实例;为了防止在外部对其实例化,将其默认构造函数和拷贝构造函数设计为私有;在单例类内部定义了一个Singleton类型的静态对象,作为外部共享的唯一实例。

用单例模式,模拟公司员工使用打印机场景,打印机可以打印员工要输出的内容,并且可以累积打印机使用次数。

class Printer{
public:
    static Printer* getInstance(){ return pPrinter;}
    void PrintText(string text){
        cout << "打印内容:" << text << endl;
        cout << "已打印次数:" << mTimes << endl;
        cout << "--------------" << endl;
        mTimes++;
    }
private:
    Printer(){ mTimes = 0; }
    Printer(const Printer&){}
private:
    static Printer* pPrinter;
    int mTimes;
};

Printer* Printer::pPrinter = new Printer;

void test(){
    Printer* printer = Printer::getInstance();
    printer->PrintText("离职报告!");
    printer->PrintText("入职合同!");
    printer->PrintText("提交代码!");
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK