设计模式系列之代理模式(Proxy)

【图文详解系列】设计模式之代理模式(Proxy Pattern) 什么是代理模式?代理模式的定义:代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。代理模式的UML图:从UML图中,可以看... 阅读详情
概述:

代理模式,顾名思义就是一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。
代理,在显示生活中有很多代理的例子,比如我们可以在售票点买到火车站的火车票,售卖点就是铁路公司的代理,Windows电脑桌面的快捷方式就是应用软件启动程序的代理。
从上面的例子可以明白代理的意图就是代替原有的对象执行该对象的功能。
那么为什么需要代理呢?不能直接访问该对象的功能吗?
因为有时候我们直接访问该对象会比较麻烦,比如 我们买火车票总不能每次跑到几十公里外的火车站去买吧,家门口的售票点就能买到火车站的火车票,简单方便;我们打开软件,总不能打开文件资源管理器,根据安装目录一层层地找到应用启动程序文件(还得记住启动程序文件地路径),多麻烦呀,在桌面放一个代理这个启动程序文件,一键启动快捷方便。

特点:

优点:

  1. 职责清晰
  2. 高扩展性
  3. 智能化

缺点:

  1. 在客户端和被代理对象之间增加了一个代理对象 ,因此有些类型的代理模式可能会造成请求处理的速度变慢
  2. 实现代理模式需要额外的工作,有些代理模式实现非常复杂

对比适配器模式和装饰器模式:

  • 适配器模式主要改变所考虑对象的接口,代理模式则不能改变所代理的对象的接口
  • 装饰器模式主要为了增强功能,代理模式是为了加以控制
使用场景:
  1. 远程代理
  2. 虚拟代理
  3. Copy-on-Write 代理
  4. 保护(Protect or Access)代理
  5. Cache代理
  6. 防火墙(Firewall)代理
  7. 同步化(Synchronization)代理
  8. 智能引用(Smart Reference)代理
实现方法:

现在我们有这样一个需求,我们需要加载一个图片返回给客户端进行展示,但是我们程序所在的这个服务器呢特别差,需要减少对象加载对内存的占用。
首先我们有一个图片展示的接口

public interface Image {

    void display();
}

然后有一个实际加载图片并实现该接口的RealImage类来实现实际的加载和展示

public class RealImage implements Image{

    private String filename;

    public RealImage (String filename){
        this.filename = filename;
        loadFromDisk(filename);
    }

    @Override
    public void display() {
        System.out.println("image display "+ filename);
    }

    private void loadFromDisk(String filename){
        // 这个方法特别占用内存
        System.out.println("image loading from disk " +filename);
    }
}

然后我们为这个特别占用内存的类创建一个代理类ImageProxy

public class ImageProxy implements Image{

    // 代理对象
    private RealImage realImage;

    private String filename;

    public ImageProxy(String filename){
        this.filename = filename;
    }

    @Override
    public void display() {
        if(realImage == null){
            realImage = new RealImage(filename);
        }

        realImage.display();
    }
}

这样客户端每次调用展示图片方法display()时通过代理类就不用每次去执行loadFromDisk()方法去加载图片了

public class ProxyTest {
    public static void main(String[] args) {
        Image image = new ImageProxy("test.jpg");

        image.display();
        System.out.println("\n");
        image.display();
    }
}

执行main方法,我们可以看到loadFromDisk()方法只被执行了一次

image loading from disk test.jpg
image display test.jpg

image display test.jpg

欢迎关注我的公众号

【愚公系列】二十三种设计模式(十二)-代理模式(Proxy Pattern) 设计模式(Design Pattern)是软件开发领域的宝贵经验,是多人反复借鉴和广泛应用的代码设计指导。它们是一系列经过分类和归纳的代码组织方法,旨在实现可重用性、可维护性和可理解性。使用设计模式,我们能够编写高质量的代码,使其更易于他人理解,并提供了代码可靠性的保证。毫无疑问,设计模式对个人、团队和整个系统都带来了显著的益处。它们将代码开发提升到工程化水平,为软件工程构建提供了坚实的基础,就如同大厦的一块块精巧的砖石一样。在项目中明智地应用设计模式可以完美地解决各种复杂问题。 阅读详情

相关推荐

DeepSeek API调用太复杂?OneAPI一站式聚合解决方案

本文介绍了OneAPI如何作为一站式聚合解决方案,简化DeepSeek API的调用流程。通过统一接口、智能路由和模型映射等核心功能,OneAPI大幅降低了多API适配的复杂性,提升开发效率。文章还提供了详细的部署指南和高阶使用技巧,帮助开发者快速实现API聚合管理。

weixin_27215337的博客 381

设计模式系列-代理模式-Proxy

代理模式可用于对原始对象增加访问控制或者审计方法参数,或者调用远程的对象方法(RPC),对于客户端来说隐藏业务额外的逻辑和复杂度。

独 coding 乐不如众 coding 乐 175

分析android逆向的学习路线

俗话说:“一入逆向深似海,从此头发是路人”。 安卓逆向作为当下热门行业“网络安全”的主要技术之一,已经受到了越来越多人的青睐。但是很多刚入门的新手小伙伴对于怎么去学习却还很是迷糊。本文就分享一下android逆向的学习路线供大家参考。 目前学习安卓逆向的人群大约分为两种: 第一种是完全没有任何基础的计算机纯小白; 第二种是本来就做开发懂编程的IT行业人员。 我们就针对这两个不同的人群做一下安卓逆向的学习路线分析。 一、无基础小白想入门 作为没有任何基础想要入门的计算机纯小白,学习上推荐参照以下步骤: (一

Hacker_by_V的博客 3077

设计模式系列之三_代理模式(Proxy)

1.什么事代理模式(Proxy Pattern)   23种java常用设计模式之一。代理模式的定义:为其他对象提供一种代理以控制对这个对象的访问。 在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象 之间起到中介的作用。 类图如下: 2.代理模式中涉及到的三个角色   (1)抽象角色:声明真实对象和代理对象的共同接口。   (2)真实角

orclight的专栏 1141

11、牛转录组分析的实用生物信息学流程

本文详细介绍了一套实用的牛转录组分析生物信息学流程,涵盖从数据提取、基因组索引生成、读取比对到单样本表达分析及差异表达分析的完整步骤。使用Angus和Brahman牛的RNA-seq数据作为示例,介绍了HTSEQ、featureCounts和StringTie等工具在基因表达计数中的应用,并结合edgeR和limma进行差异表达分析。文中提供了详细的命令行与R代码示例,包含常见问题解答与关键注意事项,帮助研究人员高效、准确地完成转录组数据分析。

ios99的博客 111

2025华为od机试真题B卷【字符串计数匹配】Java&Go 实现

给你一个字符串str和整数k,返回满足以下条件的所有子字符串个数: 1.恰好包含k个字母。 2.数字0-9各出现至少一次。

MISAYAONE的博客 639

设计模式系列(15):结构型模式 - 代理模式(Proxy)

另一个对象提供代理或占位符,以控制对它的访问。用于在访问对象时引入一定的间接性,实现额外的控制功能。

1178

模型预测控制(MPC)解析(二):单输入单输出系统

在上一篇中,为了便于说明,预测控制系统采用单输入单输出系统为例进行设计。由于系统模型使用的是状态空间方程,于是可以很容易的将这种设计方法可以扩展到多输入、多输出系统。

行者无疆的博客 8223

【图解设计模式系列】The Proxy Pattern: 代理模式

定义: 代理模式给某一个对象提供了一个代理对象,并由代理对象控制对原对象的引用。在一些情况下,一个客户端不想或者不能够直接引用一个对象,而代理对象可以在客户端和目标对象之间起到中介作用。 Proxy Pattern provides a surrogate or placeholder for another object to control access to it. Use the proxy pattern to create a representative object that control

Tech in Pieces 572

2026最新openclaw(clawbot/moltbot)真正在自己个人电脑上搭建部署,配置飞书远程远程让AI助理操控电脑完成任务,以及结合ollama无限token实现7*24小时工作(附配置)

2026最新openclaw(clawbot/moltbot)真正在自己个人电脑上搭建部署,配置飞书远程远程让AI助理操控电脑完成任务,以及结合 ollama 无限token实现7*24小时工作,以及部署安装需要的 skills 完成复杂的工作任务(附完整可以运行的配置文件)。 很多人已经会配置安装 openclaw 了 ,但是 安装完成之后真正让电脑自动运行起来的很好,完成出色工作的更少,最常见的就是聊聊天,或者执行一些简单的命令,理解要让电脑自动化工作,openclaw、skills、大模型这三样。

代码讲故事 2962

光学测量仿真软件:Zygo_(12).Zygo软件的用户界面与操作指南

Zygo软件支持用户自定义工具和插件,以扩展软件的功能和适应特定的仿真需求。编写脚本使用Python或其他支持的脚本语言编写自定义工具的脚本。例如,编写一个脚本来计算光束的衍射效率。# 示例脚本:计算光束的衍射效率 import zygo # 导入Zygo软件的API def calculate_diffraction_efficiency(wavelength , grating_period , angle) : """计算光束的衍射效率:param wavelength: 光源波长(单位:米)

kkchenjj的博客 1667

Java基础巩固系列 设计模式——代理模式(Proxy)

接口的应用:代理模式(Proxy)设计模式或静态代理模式 概述:为其他对象提供一种代理以控制对这个对象的访问 代码示例: public class TestProxy { public static void main(String[] args) { Object obj = new ProxyObject(); obj.action(...

Peter__Li的博客 184

SAP 合并报表(EC-CS)完整方法论 + 全业务操作步骤

SAP合并报表(EC-CS)方法论与操作指南摘要 SAP EC-CS模块提供完整的集团合并解决方案,其核心方法论基于会计准则和集团管控逻辑,通过6大维度构建标准化合并体系:组织架构标准化、数据采集标准化、外币换算规则化、内部交易自动化抵消、股权与商誉规范化、报表出具灵活化。 实施过程分为两个阶段: 上线前配置阶段(12个步骤):包括合并架构搭建、科目表配置、外币规则设定、抵消规则定义等基础工作 日常操作阶段(10个步骤):涵盖数据报送、外币换算、内部对账、自动抵消、调整分录等月结流程 系统优势包括: 支持多

金牌架构师 1364

【JAVA进阶系列】JAVA 设计模式 -- 代理模式(Proxy)

【JAVA进阶系列】JAVA 设计模式 -- 代理模式(Proxy) 【1.1】代理模式简介与 JAVA 代码示例 【1.1】代理模式简介 代理模式的类结构图 代理模式中的角色 1. Subject(主体),Subject 角色定义了使 Proxy 角色和 RealSubject 角色之间具有一致性的接口;由于存在 Subject 角色,Client 角色不必在意其所使用的究竟是 Proxy 角色还是 RealSubject 角色; 2. Proxy(代理人),Proxy 会尽量处理来自 Cli

CopperSun 技术博客 384

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

C#设计模式系列:代理模式(Proxy)

  代理模式提供了一个中介控制对某个对象的访问。现实生活中,我们可能会用支票在市场交易中用来代替现金,支票就是账户中资金的代理。 1、代理模式简介 1.1>、定义     代理模式(Proxy)定义:代理模式为客户端程序提供一种中间层以控制对这个对象的访问。 1.2>、使用频率    中高 2、代理模式结构 2.1>、结构图 2.2>、参与者   代理...

weixin_34115824的博客 139

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

设计模式总结篇系列:代理模式(Proxy)

时代在发展,我们发现,现在不少明星都开始进行微访谈之类的,有越来越多的参与捐赠等。新的一天开始了,首先看下新的一天的日程安排: 1 interface Schedule{ 2 3 public void weiTalk(); 4 5 public void donation(); 6 7 } Schedule接口定义了今天的形成

xingjiehp的专栏 291

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

C#设计模式系列:代理模式(Proxy Pattren)

一、引言 在软件开发过程中,有些对象有时候会由于网络或者其他的障碍,以至于不能够或者不能直接访问到这些对象,如果直接访问对象给系统带来不必要的复杂性,这时候可以在客户端和目标对象之间增加一层中间层,让代理对象代替目标对象,然后客户端只需要访问代理对象,由代理对象去帮我们去请求目标对象并返回结果给客户端,这样的一个解决思路就是今天要介绍的 代理模式(Proxy Pattern)二、代理模式的详细...

weixin_33816821的博客 190

【设计模式系列学习笔记】7、代理模式 - proxy pattern

代理模式核心作用: 通过代理,控制对象的访问;可以详细控制访问某个对象的方法,在调用方法前做前置处理,调用方法后做后置处理; 代理模式的应用: 远程代理,为一个对象在不同的地址空间提供局部代表;这样可以隐藏一个对象存在于不同地址空间的事实; 虚拟代理,根据需要创建开销很大的对象,通过虚拟代理来存放实例化需要很长时间的真实对象;如浏览器加载图片时通过虚拟代理来替代了真实的图片,此时代理存储了...

hellboy0621的博客 135

研磨设计模式 之 代理模式(Proxy)2——跟着cc学设计系列

  11.2  解决方案 11.2.1  代理模式来解决 用来解决上述问题的一个合理的解决方案就是代理模式。那么什么是代理模式呢? (1)代理模式定义   (2)应用代理模式来解决的思路 仔细分析上面的问题,一次性访问多条数据,这个可能性是很难避免的,是客户的需要。也就是说,要想节省内存,就不能从减少数据条数入手了,那就只能从减少每条数据的数据量上来考虑。 一个基本的思路如下...

跟着cc学设计 私塾在线学习网 http://sishuok.com 196

极速理解设计模式系列:3.代理模式(Proxy Pattern)

三个角色:实体接口(Subject),真实实体(RealSubject),代理实体(Proxy) 实体接口(Subject):目标对象的抽象接口 真实实体(RealSubject):目标对象的具体实现. 代理实体(Proxy):同样实现Subject接口,但是在方法内部是调用真实实体的相应方法实现功能点,而非代理类自己去处理事务。 ...

weixin_30675247的博客 69
上一篇: 设计模式系列之装饰器模式(Decorator)
下一篇: 设计模式系列之桥接模式(Bridge)
工程师小哥
博客等级 码龄10年 4粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值