设计模式之单例模式(一)

一、前言

        在编写应用程序的时候,用到一些编程技巧是难免的。在学习编程的时候,个人体会是思维更重要,编程语言只是一个表达思维的工具,所以对于面向对象的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

投入如

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值