c++代理类

 

想必大家都知道在浏览器中设置代理吧!??
其实代理模式跟这个差不多,对象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类对象,即代理类对象,所有的操作都是调用代理类的公有函数,间接操作实现类。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值