当前位置: 首页 > article >正文

结构型模式---代理模式

概念

代理模式是一种结构型模式,主要用于在客户端和接口之间添加一个中间层,用于在客户端和接口之间进行权限控制或者其他的中间层操作。

使用场景

1、延缓初始化,当我们偶尔需要使用一个重量级的服务对象,如果一直保持该对象的运行会消耗大量的系统资源,这时候就可以使用代理。也可以控制重量级的对象进行即可销毁。

2、权限访问控制,当我们希望特定的客户端使用接口的时候,就可以使用代理模式。当复合我们的条件的时候再进行真正的接口访问。

3、本地执行远程服务(远程代理),这个时候使用代理进行远程服务的复杂处理。并且可以缓存请求结果。

4、记录日志,当需要在接口和客户端之前进行日志记录的时候可以使用代理模式。

创建方式

1、如果有现成的服务器接口我们可以直接继承服务器接口实现代理类,如果没有现成的服务接口,我们就需要创建一个接口来实现服务对象和代理的可交换性。。

2、创建代理类,其中必须包含一个指向服务接口的引用或者成员变量。一般情况下代理完全管理服务接口的生命周期。

3、根据需求实现代理接口。

类关系结构

在这里插入图片描述

示例代码

#include <iostream>
#include "DaiLiMoShi.h"

int main()
{
    std::cout << "欢迎东哥来到设计模式的世界!\n";
    Proxy proxy;
    proxy.setSerivePate("193.101.10.9", 2493);
    int post = proxy.getSerivePost();
    cout << "main打印获取服务post数据" << endl;
    cout << "Post : " << post << endl;
}
#pragma once
#include <string>
#include <iostream>
using namespace std;
class BaseProxyInterFaxe
{
public:
	BaseProxyInterFaxe() {}
	~BaseProxyInterFaxe() {}
	virtual int getSerivePost();
	virtual void setSerivePate(string ip, int post);
};

class ThirdSerice : public BaseProxyInterFaxe {
public:
	ThirdSerice() {}
	~ThirdSerice() {}
	int getSerivePost() override;
	void setSerivePate(string ip, int post) override;
private:
	string m_ip;
	int m_post;
};

class Proxy : public BaseProxyInterFaxe {
public:
	Proxy() {}
	~Proxy() {}
	int getSerivePost() override;
	void setSerivePate(string ip, int post) override;
private:
	ThirdSerice _thirdSerice;
};
#include "DaiLiMoShi.h"

int BaseProxyInterFaxe::getSerivePost()
{
    return 0;
}

void BaseProxyInterFaxe::setSerivePate(string ip, int post)
{ 
    //基类操作
}

int Proxy::getSerivePost()
{
    //此处可以添加数据打印、权限判断等
    cout << "代理打印获取服务post数据" << endl;
    cout << "Post : " << _thirdSerice.getSerivePost() << endl;
    return _thirdSerice.getSerivePost();
}

void Proxy::setSerivePate(string ip, int post)
{
    //此处可以添加数据打印、权限判断等
    cout << "代理设置服务位置" << endl;
    cout << "IP : " << ip << endl;
    cout << "Post : " << post << endl;
    _thirdSerice.setSerivePate(ip, post);
}

int ThirdSerice::getSerivePost()
{
    return m_post;
}

void ThirdSerice::setSerivePate(string ip, int post)
{
    m_ip = ip;
    m_post = post;
}


http://www.kler.cn/a/549465.html

相关文章:

  • EasyRTC视频通话WebP2P技术:轻量化SDK助力嵌入式设备实时音视频通信
  • Vue.js 组件开发深入解析:Vue 2 vs Vue 3
  • 【漫话机器学习系列】094.交叉熵(Cross-Entropy)
  • 数据结构------单向链表。
  • 苍穹外卖day4 redis相关简单知识 店铺营业状态设置
  • Linux 基础IO——重定向和缓冲区
  • 大疆无人机需要的kml文件如何制作kml导出(大疆KML文件)
  • Instagram与小红书的自动化运营
  • Vite入门指南
  • github用户名密码登陆失效了
  • Mac上搭建宝塔环境并部署PHP项目
  • Ubuntu 连接 air pods
  • ios中常见的设计原则和设计模式
  • ARINC 429详解
  • CSS Grid 网格布局,以及 Flexbox 弹性盒布局模型,它们的适用场景是什么?
  • VS Code User和System版区别【推荐使用System版本】and VSCode+Keil协同开发之Keil Assistant
  • 【ISO 14229-1:2023 UDS诊断(会话控制0x10服务)测试用例CAPL代码全解析③】
  • ffmpeg-cli-wrapper操作ffmpeg的工具
  • Anaconda +Jupyter Notebook安装(2025最新版)
  • 问卷数据分析|SPSS实操之量表描述性统计