抽象代理模式2.0版本

前言:

1.0版本的核心

代理的定义 = A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper(封装) or agent object that is being called by the client to access the real serving object behind the scenes

The Proxy design pattern allows you to provide an interface to other objects by creating a

wrapper(封装) class as the proxy. The wrapper class, which is the proxy, can add additional

functionality to the object of interest without changing the object's code.

翻译:代理,在其最普遍的形式中,是一个作为与其他事物接口的类。代理可以连接任何接口:网络连接、内存中的大型对象、文件,或者其他昂贵或难以复制的资源。简而言之,代理是客户端(主语)调用的封装器或代理对象,(目的)用于访问幕后真正的业务对象

代理设计模式允许你通过创建一个封装类作为代理,为其他对象提供接口。作为代理的封装类可以在不更改对象代码的情况下为其添加额外的功能,而无需更改对象的代码。

1.封装类

举个例子就知道了,封装了一个产品的名字

java 复制代码
package proxy;

public class wrapper {
    private String name;

    public wrapper(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

你可能觉得,封装类很像实体类,并不然,封装类其实是实体类的上一级

2.0的全新核心

单一产品

多个产品

正片:

单一产品

第一步:新建一个封装类(产品)

结构组成:私有访问变量 + 有参构造 + toStiring方法(函数)重构

第二步:新建一个业务对象(代理商)

java 复制代码
package proxy;

public class wrapperIMP {
    public void enter(wrapper wrapper) {
        System.out.println(wrapper + " 欢迎来到站长的自言自语.");
    }
}

结构组成:无返回值enter方法

第三步:一个封装类作为代理(代理人)

java 复制代码
public class wrapperR extends wrapperIMP {

    private static final int NUM_WIZARDS_ALLOWED = 3;

    private int i;

    @Override
    public void enter(wrapper wrapper) {
        if (i < NUM_WIZARDS_ALLOWED) {
            super.enter(wrapper);
            i++;
        } else {
            System.out.println(wrapper + "哈哈害!");
        }
    }
}

结构组成:继承wrapperIMP + 重构了父类的enter方法 (条件判断 )

第四步:模仿接口传入值

java 复制代码
public class app {
    public static void main(String[] args) {

        wrapperR tower = new wrapperR();
        tower.enter(new wrapper("小红"));
        tower.enter(new wrapper("小明"));
        tower.enter(new wrapper("小黄"));
        tower.enter(new wrapper("小白"));
        tower.enter(new wrapper("小黑"));
    }
}

结构组成:new 一个代理人当成变量 + 调用代理人的enter方法

第五步运行:

发现没,代理模式中,我们的代码是全程一直走的,直到结束

相关推荐
柒.梧.8 天前
Java代理模式精讲:静态代理+JDK动态代理
java·开发语言·代理模式
Forget_85509 天前
RHEL——HAProxy模式
代理模式
mjhcsp12 天前
C++ 树形 DP解析
开发语言·c++·动态规划·代理模式
不想看见40412 天前
House Robber 基本动态规划:一维--力扣101算法题解笔记
笔记·算法·leetcode·代理模式
忘梓.15 天前
解锁动态规划的奥秘:从零到精通的创新思维解析(10)
c++·算法·动态规划·代理模式
HEU_firejef17 天前
设计模式——代理模式
设计模式·代理模式
香芋Yu18 天前
【强化学习教程——01_强化学习基石】第03章_动态规划与策略迭代
算法·动态规划·代理模式
J_liaty25 天前
23种设计模式一代理模式
设计模式·代理模式
短剑重铸之日1 个月前
《设计模式》第九篇:三大类型之结构型模式
java·后端·设计模式·组合模式·代理模式·结构性模式
B2_Proxy1 个月前
如何使用代理服务解决“您的 ASN 被阻止”错误:全面策略分析
网络·爬虫·网络协议·tcp/ip·安全·代理模式