一、前言
在编写应用程序的时候,用到一些编程技巧是难免的。在学习编程的时候,个人体会是思维更重要,编程语言只是一个表达思维的工具,所以对于面向对象的Java/C++都适用,其他语言一样,可能就是在语言规则有小小的差异。
在面向对象程序的设计中,开发需求是需要一个可给其他任何类提供资源的类。当然,可以选择使用全局变量来实现,类里面N多个static关键字,但类中的静态变量必须要定义分配内存,且全局变量并不能防止实例化多个对象,这样对代码的管理只会更加复杂化。本文主要介绍下单例类的使用,即单例模式。它可以实现一个类仅有一个实例,并提供一个访问它的全局访问点。
1、静态数据成员在定义或说明时前面加关键字static。//静态变量的定义
自其初始化就一直存在, 直至程序结束才生命over的那些变量
士大夫十分
二、源码的讲解
11111111111111111111111111111
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* instance();
void singletonMethod();
protected:
Singleton();
private:
static Singleton* _instance;
};
#endif
2222222222222
#include "singleton.h"
#include <iostream>
using namespace std;
Singleton* Singleton::_instance = NULL;//在类的外面定义,实际上是给静态成员变量分配内存
Singleton::Singleton() {
cout<<"Initializing singleton constructor completely"<<endl;
}
Singleton* Singleton::instance() {
cout<<"Excute the function to initialize static variable"<<endl;
if (_instance == NULL) {
cout<<"static variable is NULL, then excuting singleton constructor"<<endl;
_instance = new Singleton();
}else{
cout<<"static variable is not NULL, then returnning the static variable"<<endl;
}
return _instance;
}
void Singleton::singletonMethod()
{
cout<<"Excute common method"<<endl;
}
333333333333333333
#include "singleton.cpp"
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc,char* argv[]) {
Singleton* sgn = Singleton::instance();
printf("---------------------------------------------------------\n");
Singleton::instance()->singletonMethod();
return 0;
}
4444444444444444
default:
@g++ singletonTest.c -o singletonTest
./singletonTest
clean:
@rm singletonTest -f
7777777777777
投入如