现在的位置: 首页 > 综合 > 正文

c++代理类

2013年10月29日 ⁄ 综合 ⁄ 共 1823字 ⁄ 字号 评论关闭

原文地址:http://www.gobee.cn/article/200694/157/157650.Html

 

 

想必大家都知道在浏览器中设置代理吧!??
其实代理模式跟这个差不多,对象A(相当于浏览器)不是直接访问对象C(相当Web服务器),而是通过一个中间对象B(相当于代理服务器)间接访问对象C。对象B则可以利用这一有利位置为A提供一个与C完全不同的接口,或做一些C本来不做的事!流程如下图所示:

A -----> B ------> C

这样B就是C的代理类,C可被称作实现类,A是客户代码。

==================
下面是源代码,一共4个文件。其中实现类成员函数为全部写成内联函数。
1. 实现类文件implementation.h:
// implementation.h --
// 2006-07-21 14:20

#ifndef IMPLEMENTATION_H_
#define IMPLEMENTATION_H_

class Implementation {
public:
Implementation(int v) { value = v; }
void setValue(int v) { value = v; }
int  getValue() const { return value; }

private:
int value;
};
#endif

2. 代理类头文件interface.h:
// interface.h -- Interface类是Implementation类的代理类
// 2006-07-21 14:23

#ifndef INTERFACE_H_
#define INTERFACE_H_

class Implementation;  // forward class declaration

class Interface {      // Interface代理类
public:
Interface(int v);
void setValue(int v);
int  getValue() const;
~Interface();

private:
Implementation * ptr;
};

#endif

3. 代理类实现文件interface.cpp:
// interface.cpp
// 2006-07-21 14:25

#include "implementation.h"
#include "interface.h"

Interface::Interface(int v) : ptr(new Implementation(v)) {
}

void Interface::setValue(int v) {
ptr->setValue(v);
}

int Interface::getValue() const {
return ptr->getValue();
}

Interface::~Interface() {
delete ptr;
}

4. 客户代码,这里只是一个主函数,使用代理模式,文件:useproxy.cpp:
// useproxy.cpp -- Use proxy class
// 2006-07-21 14:29

#include <iostream>
#include "implementation.h"
#include "interface.h"
using namespace std;

int main() {
Interface i(5);

cout << "Interface contains: " << i.getValue() << " before setValue/n";

i.setValue(10);
cout << "Interface contains: " << i.getValue() << " after setValue/n";
return 0;
}

=======================
运行结果:
Interface contains: 5 before setValue
Interface contains: 10 after setValue
Press any key to continue

=========================
说明:在useproxy.cpp文件中,只有一个Interface类对象,即代理类对象,所有的操作都是调用代理类的公有函数,间接操作实现类。

 

抱歉!评论已关闭.