代理模式实现为别人做嫁衣 C++

本文通过送礼示例介绍了代理模式的概念及其实现方式。代理模式通过使用代理对象来替代实际对象,实现对目标对象操作的间接控制。文中给出了具体的C++代码实现,并展示了如何通过代理模式进行送礼物的模拟。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说下对代理模式的理解,代理模式就是用代理对象来替代实际对象,完成实际对象应该完成的操作,如给妹子送花, 或者打怪升级。
本质上, 他就是在访问对象的时候, 加入了一定程度的间接性, 通过这种间接性可以实现各种用途。
UML:
这里写图片描述
运行效果图
这里写图片描述

代码:
target.h

#ifndef _TARGET_H_
#define _TARGET_H_

#include <string>

class CTargetGirl{
public:
    CTargetGirl(std::string name) : name(name){}
    std::string Name() const { return name; }
    void Name(std::string val) { name = val; }

private:
    std::string name;   
};

#endif // _TARGET_H_

operation.h

#ifndef _OPERATION_H_
#define _OPERATION_H_

class CIOperation{
public:
    virtual void GiveDolls() const = 0;
    virtual void GiveFlowers() const = 0;
    virtual void GiveChocolates() const = 0;
};

#endif // _OPERATION_H_

persuit.h

#ifndef _PERSUIT_H_
#define _PERSUIT_H_

#include "target.h"
#include "operation.h"
#include <memory>
#include <iostream>

class CPersuit : public CIOperation{
public:
    CPersuit(CTargetGirl * _girl) : girl(_girl){}
    void GiveDolls() const { std::cout << girl->Name() << " give you dolls" << std::endl; }
    void GiveFlowers() const { std::cout << girl->Name() << " give you flowers" << std::endl; }
    void GiveChocolates() const { std::cout << girl->Name() << " give you chocolates" << std::endl; }

private:
    CTargetGirl * girl;
};

#endif // _PERSUIT_H_

proxy.h

#ifndef _PROXY_H_
#define _PROXY_H_

#include "persuit.h"
#include "operation.h"
#include <memory>
#include <iostream>

class CProxy : public CIOperation{
public:
    CProxy(CTargetGirl * _girl){ persuit = std::shared_ptr<CPersuit>(new CPersuit(_girl)); }
    void GiveDolls() const { persuit->GiveDolls(); }
    void GiveFlowers() const { persuit->GiveFlowers(); }
    void GiveChocolates() const { persuit->GiveChocolates(); }

private:
    std::shared_ptr<CPersuit> persuit;
};

#endif // _PROXY_H_

main.cpp

#include "proxy.h"
#include <iostream>
#include <memory>

using namespace std;

int main(){
    shared_ptr<CTargetGirl> girl(new CTargetGirl("jiaojiao"));
    shared_ptr<CProxy> proxy(new CProxy(girl.get()));

    proxy->GiveDolls();
    proxy->GiveFlowers();
    proxy->GiveChocolates();

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值