概要
单件模式,对于我来说,一直觉得是是一直控制对象数量的方法,但知道今天我才发现他对降低耦合度的作用。
其实对于单件有两个明显的价值,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);
}
运行结果