抽象代理模式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方法

第五步运行:

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

相关推荐
Zyy~1 天前
《设计模式》代理模式
设计模式·代理模式
melonbo2 天前
代理模式C++
c++·设计模式·系统安全·代理模式
啊阿狸不会拉杆6 天前
《算法导论》第 15 章 - 动态规划
数据结构·c++·算法·排序算法·动态规划·代理模式
王彬泽9 天前
【设计模式】代理模式
设计模式·代理模式
是店小二呀13 天前
【动态规划 | 子序列问题】子序列问题的最优解:动态规划方法详解
算法·动态规划·代理模式
恣艺13 天前
LeetCode 132:分割回文串 II
算法·leetcode·代理模式
困鲲鲲19 天前
设计模式:代理模式 Proxy
设计模式·代理模式
魑魅魍魉都是鬼19 天前
随缘玩 一: 代理模式
android·java·代理模式
超浪的晨20 天前
Java 代理机制详解:从静态代理到动态代理,彻底掌握代理模式的原理与实战
java·开发语言·后端·学习·代理模式·个人开发
蝸牛ちゃん21 天前
设计模式(十三)结构型:代理模式详解
设计模式·系统架构·代理模式·软考高级