F_ProxyPattern.h
#pragma once
/*
代理模式(Proxy Pattern)
1.一个类代表另一个类的功能;
2.意图: 为其他对象提供一种代理(类),以控制对这个类的访问;
3.何时使用: 想访问一个类时,做一些控制
4.实现: 增加中间层(类)
5.关键代码: 实现与中间类的组合
6.优点: 职责清晰化, 可扩展性, 智能化
7.缺点: 增加额外的中间层开销,影响效率,有的代理类很复杂
*/
//基类
class FileMangerBase
{
public:
virtual BOOL DeleteFile() = 0;
virtual BOOL CopyFile() = 0;
};
//实现类
class FileManger: public FileMangerBase
{
public:
FileManger(PCSTR sSrcPath, PCSTR sDestPath = NULL);
FileManger();
~FileManger();
public:
BOOL CopyFile();
BOOL DeleteFile();
void SetDestPath(const PCSTR sDestPath);
void SetSrcPath(const PCSTR sSrcPath);
void SetPath(const PCSTR sSrcPath, const PCSTR sDestPath = NULL);
private:
PCSTR m_sDestPath;
PCSTR m_sSrcPath;
};
//代理类: 中间层,对实现类的控制
class FileMangerProxy:public FileMangerBase
{
public:
FileMangerProxy(const FileManger &fileManger);
FileMangerProxy(const PCSTR sSrcPath, const PCSTR sDestPath = NULL);
~FileMangerProxy();
public:
BOOL CopyFile();
BOOL DeleteFile();
void SetMangerTxt(BOOL bTxt);
private:
FileManger m_FileManger;
BOOL m_bTxt;
};
F_ProxyPatern.cpp
#include "StdAfx.h"
#include "F_ProxyPattern.h"
FileManger::FileManger(PCSTR sSrcPath, PCSTR sDestPath)
:m_sSrcPath(sSrcPath), m_sDestPath(sDestPath)
{}
FileManger::FileManger()
{}
FileManger::~FileManger()
{
}
void FileManger::SetDestPath(const PCSTR sDestPath)
{
m_sDestPath = sDestPath;
}
void FileManger::SetSrcPath(const PCSTR sSrcPath)
{
m_sSrcPath = sSrcPath;
}
void FileManger::SetPath(const PCSTR sSrcPath, const PCSTR sDestPath)
{
m_sSrcPath = sSrcPath;
m_sDestPath = sDestPath;
}
BOOL FileManger::CopyFile()
{
TRACE("\n\n FileManger::CopyFile() => m_sSrcPath: %s\n\n", m_sSrcPath);
return TRUE;
}
BOOL FileManger::DeleteFile()
{
TRACE("\n\n FileManger::DeleteFile() => m_sSrcPath: %s\n\n", m_sSrcPath);
return TRUE;
}
FileMangerProxy::FileMangerProxy(const FileManger &fileManger)
:m_FileManger(fileManger)
{}
FileMangerProxy::FileMangerProxy(const PCSTR sSrcPath, const PCSTR sDestPath)
{
m_FileManger.SetPath(sSrcPath, sDestPath);;
}
FileMangerProxy::~FileMangerProxy()
{}
void FileMangerProxy::SetMangerTxt(BOOL bTxt)
{
m_bTxt = bTxt;
}
BOOL FileMangerProxy::CopyFile()
{
BOOL bCopyFile(FALSE);
if (m_bTxt)
{
bCopyFile = m_FileManger.CopyFile();
}
return bCopyFile;
}
BOOL FileMangerProxy::DeleteFile()
{
BOOL bDeleteFile(FALSE);
if (m_bTxt)
{
bDeleteFile = m_FileManger.DeleteFile();
}
return bDeleteFile;
}
F_ProxyPattern_Test.h
#pragma once
#include "F_ProxyPattern.h"
void F_ProxyPattern_Test()
{
FileManger FileMangerO("C:\\TestRFile.cpp", "C:\\TestWFile.cpp");
FileMangerProxy fileMangerProxy1(FileMangerO);
fileMangerProxy1.SetMangerTxt(FALSE);
fileMangerProxy1.CopyFile();
fileMangerProxy1.DeleteFile();
FileMangerProxy fileMangerProxy2("C:\\TestRFile.cpp", "C:\\TestWFile.cpp");
fileMangerProxy2.SetMangerTxt(TRUE);
fileMangerProxy2.CopyFile();
fileMangerProxy2.DeleteFile();
}