我所做的工作上的程序主要是处理‘消息’的,简单点就是将‘消息’从一端搬到另一端,这样的过程就需要一个对象负责记录搬运次数,这个对象可以叫做‘统计’对象--CStatObject。
在开始写统计对象时,我一直是根据有几个统计项,就定义几个统计变量,样子类似如下:
#ifndef __STATOBJECT_H__
#define __STATOBJECT_H__
#include <iostream>
class CStatObject
{
public:
enum StatType { ST_SOAP_NOTIFY = 0, ST_SOAP_SEND, ST_APP_NOTIFY, ST_APP_SEND };
public:
CStatObject();
virtual ~CStatObject() {}
void Init();
int Inc(StatType type, bool req);
void Show(std::ostream& os) const;
private:
size_t m_szSOAPNotifyReq;
size_t m_szSOAPSendReq;
size_t m_szAppNotifyReq;
size_t m_szAppSendReq;
size_t m_szSOAPNotifyResp;
size_t m_szSOAPSendResp;
size_t m_szAppNotifyResp;
size_t m_szAppSendResp;
};
#endif
如上代码可以看出,如果需要统计的项目过多时,变量的定义就变成一个很繁琐的事情。因此,根据统计项的特点--每个统计项目都有请求和应答两项,于是,再简化如下:
#ifndef __STATOBJECT_H__
#define __STATOBJECT_H__
#include <iostream>
#include <map>
class CStatObject
{
public:
enum StatType { ST_SOAP_NOTIFY = 0, ST_SOAP_SEND, ST_APP_NOTIFY, ST_APP_SEND };
typedef std::pair<size_t, size_t> TCountPair;
public:
CStatObject();
virtual ~CStatObject() {}
void Init();
int Inc(StatType type, bool req);
void Show(std::ostream& os) const;
private:
TCountPair m_szSOAPNotify;
TCountPair m_szSOAPSend;
TCountPair m_szAppNotify;
TCountPair m_szAppSend;
};
#endif
嗯,省了一半。但要是统计项目本身很多时,还是会需要定义很多的变量,于是,再次精简如下:
#ifndef __STATOBJECT_H__
#define __STATOBJECT_H__
#include <iostream>
#include <map>
class CStatObject
{
public:
enum StatType { ST_SOAP_NOTIFY = 0, ST_SOAP_SEND, ST_APP_NOTIFY, ST_APP_SEND };
typedef std::pair<size_t, size_t> TCountPair;
typedef std::map<StatType, TCountPair> TStatMap;
public:
CStatObject();
virtual ~CStatObject() {}
void Init();
int Inc(StatType type, bool req);
void Show(std::ostream& os) const;
private:
TStatMap _mapStat;
};
#endif
嘿嘿,现在这个样子,不论统计项目如何变化,变量永远就这一个了~总结来说:偷懒使人进步~
这里是实现部分,一样的繁琐,但比前两种,还是省了很多行代码的~
#include "StatObject.h"
CStatObject g_stStatObject;
CStatObject::CStatObject()
{
Init();
}
void CStatObject::Init()
{
_mapStat.clear();
_mapStat.insert(std::make_pair(ST_SOAP_NOTIFY, std::make_pair(0,0)));
_mapStat.insert(std::make_pair(ST_SOAP_SEND, std::make_pair(0,0)));
_mapStat.insert(std::make_pair(ST_APP_NOTIFY, std::make_pair(0,0)));
_mapStat.insert(std::make_pair(ST_APP_SEND, std::make_pair(0,0)));
}
int CStatObject::Inc(CStatObject::StatType type, bool req)
{
TStatMap::iterator it = _mapStat.find(type);
if(it == _mapStat.end())
return -1;
if(req)
++ it->second.first;
else
++ it->second.second;
return 0;
}
void CStatObject::Show(std::ostream& os) const
{
os << "\n--- Stat Info ---";
for(TStatMap::const_iterator it = _mapStat.begin(); it != _mapStat.end(); ++ it)
{
switch(it->first)
{
case ST_SOAP_NOTIFY:
os << "\nSOAP Notify = ";
break;
case ST_SOAP_SEND:
os << "\nSOAP Send = ";
break;
case ST_APP_NOTIFY:
os << "\nApp Notify = ";
break;
case ST_APP_SEND:
os << "\nApp Send = ";
break;
default:
os << "\nIMPOSSIBLE = ";
}
os << it->second.first << "/" << it->second.second << "(req/resp)";
}
}