C++单例模式初学分享

来源:互联网 发布:仿58同城源码 php 编辑:程序博客网 时间:2024/05/29 19:02

单例模式顾名思义就是只有一个实例,单例模式有以下三个特点:

1,一个类只有一个实例;

2,这个类自行创建实例;

3,必须向整个系统提供一个全局访问点,该实例被所有的程序模块所共享。

实现单例模式据我所知一般有两个方法,其一使用全局变量,其二使用静态成员函数。

一,首先介绍不经常(我觉得)使用的全局变量实现单例模式:

把所有的构造函数声明为私有,则不能创建任何对象。如果允许只创建一个对象,可用一个全局函数(或静态成员函数)来创建唯一的一个静态对象,并返回其引用,为提高效率,可把全局函数声明为inline。注意这个全局函数要声明为类的友元函数,因为要使用私有的构造函数

1,在类Printer的private中声明友元函数friend Printer* thePrinter();

2,inline Printer* thePrinter(){ static Printer p;  return p; }

二,介绍经常使用的静态成员函数法:

instance.h

#ifndef _INSTANCE_#define _INSTANCE_class Singleton{public: static Singleton *GetInstance();protected:Singleton(){}private:static Singleton *instance;class Rabbit{public:~Rabbit(){if (Singleton::instance){delete Singleton::instance;}}};static Rabbit Gar;};#endif
instance.cpp
#include "instance.h"#include <iostream>Singleton* Singleton::instance = NULL;//静态变量使用前必须先初始化Singleton* Singleton::GetInstance(){if (Singleton::instance == NULL){Singleton::instance = new Singleton();}return instance;}
main.cpp
#include "instance.h"#include <iostream>using namespace std;int main(){Singleton *s = Singleton::GetInstance();return 0;}
程序在结束时析构全局变量和静态成员变量的特性。

原创粉丝点击