c++ 单件模式解耦应用

22 篇文章 1 订阅

概要

单件模式,对于我来说,一直觉得是是一直控制对象数量的方法,但知道今天我才发现他对降低耦合度的作用。

其实对于单件有两个明显的价值,1对象的个数少,对这个对象的成员对象的操作能够统一起来,其实对于很多功能职责的类,都是有这个要求的。我们通常用桥接的方式来解决问题,但是用单实例明显更灵活。

代码

// Log.h: interface for the Log class.
//
//

#if !defined(AFX_LOG_H__8BA2CF72_E906_4643_81FE_42554F769933__INCLUDED_)
#define AFX_LOG_H__8BA2CF72_E906_4643_81FE_42554F769933__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class Log  
{
public:
	Log();
	int fun(int a);
	static Log* mLog;
	static Log* getMy();
	virtual ~Log();

};

#endif // !defined(AFX_LOG_H__8BA2CF72_E906_4643_81FE_42554F769933__INCLUDED_)

代码

// Log.cpp: implementation of the Log class.
//
//

#include "stdafx.h"
#include "sigleTest.h"
#include "Log.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//
// Construction/Destruction
//
Log* Log::mLog = 0;
Log::Log()
{

}
int Log::fun(int a){
	return a*a;
}
Log* Log::getMy(){
	if(mLog==0){
		mLog = new Log();	
	}
	return mLog;
}
Log::~Log()
{

}

 

void CSigleTestDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	int r = Log::getMy()->fun(5);
	CString c;
	c.Format("%d",r);
	m_Edit.SetWindowText(c);
}

运行结果 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值