DesignPattern/13.ProxyPattern/2.Code/ProxyPattern.h

73 lines
1.2 KiB
C
Raw Normal View History

2019-10-29 14:14:19 +00:00
#ifndef __FLYPATTERN_PATTERN_H__
#define __FLYPATTERN_PATTERN_H__
#include <mutex>
#include <time.h>
using namespace std;
// 抽象主题角色
2019-10-29 14:14:19 +00:00
class Subject
{
public:
Subject(){}
virtual ~Subject(){}
2019-10-29 14:14:19 +00:00
virtual void method() = 0;
};
// 真实主题角色
2019-10-29 14:14:19 +00:00
class RealSubject :public Subject
{
public:
RealSubject(){}
virtual ~RealSubject(){}
2019-10-29 14:14:19 +00:00
void method(){
printf("调用业务方法\n");
2019-10-29 14:14:19 +00:00
}
};
// Log类
2019-10-29 14:14:19 +00:00
class Log
{
public:
Log(){}
string getTime(){
time_t t = time(NULL);
char ch[64] = { 0 };
//年-月-日 时:分:秒
2019-10-29 14:14:19 +00:00
strftime(ch, sizeof(ch)-1, "%Y-%m-%d %H:%M:%S", localtime(&t));
return ch;
}
};
// 代理类
2019-10-29 14:14:19 +00:00
class Proxy:public Subject
{
public:
Proxy(){
realSubject = new RealSubject();
log = new Log();
}
~Proxy(){
delete realSubject;
delete log;
realSubject = nullptr;
log = nullptr;
}
2019-10-29 14:14:19 +00:00
void preCallMethod(){
printf("方法method()被调用,调用时间为%s\n",log->getTime().c_str());
2019-10-29 14:14:19 +00:00
}
void method(){
preCallMethod();
realSubject->method();
postCallMethod();
}
void postCallMethod(){
printf("方法method()调用调用成功!\n");
2019-10-29 14:14:19 +00:00
}
private:
RealSubject *realSubject;
Log* log;
};
#endif //__FLYPATTERN_PATTERN_H__