Java 代理模式讲解和代码示例

简介: Java 代理模式讲解和代码示例

使用示例尽管代理模式在绝大多数 Java 程序中并不常见 但它在一些特殊情况下仍然非常方便 当你希望在无需修改客户代码的前提下于已有类的对象上增加额外行为时 该模式是无可替代的

Java 标准程序库中的一些代理模式的示例

  • java.lang.reflect.Proxy
  • java.rmi.*
  • javax.ejb.EJB 查看评论
  • javax.inject.Inject 查看评论
  • javax.persistence.PersistenceContext

识别方法代理模式会将所有实际工作委派给一些其他对象 除非代理是某个服务的子类 否则每个代理方法最后都应该引用一个服务对象

01缓存代理

在本例中 代理模式有助于实现延迟初始化 并对低效的第三方 YouTube 集成程序库进行缓存

当你需要在无法修改代码的类上新增一些额外行为时 代理模式的价值无可估量


02some_cool_media_library


some_cool_media_library/ThirdPartyYouTubeLib.java: 远程服务接口
package refactoring_guru.proxy.example.some_cool_media_library;import java.util.HashMap;public interface ThirdPartyYouTubeLib {    HashMap<String, Video> popularVideos();    Video getVideo(String videoId);
}

some_cool_media_library/ThirdPartyYouTubeClass.java: 远程服务实现

package refactoring_guru.proxy.example.some_cool_media_library;import java.util.HashMap;public class ThirdPartyYouTubeClass implements ThirdPartyYouTubeLib {    @Override
    public HashMap<String, Video> popularVideos() {        connectToServer("http://www.youtube.com");        return getRandomVideos();
    }    @Override
    public Video getVideo(String videoId) {        connectToServer("http://www.youtube.com/" + videoId);        return getSomeVideo(videoId);
    }    // -----------------------------------------------------------------------
    // Fake methods to simulate network activity. They as slow as a real life.
    private int random(int min, int max) {        return min + (int) (Math.random() * ((max - min) + 1));
    }    private void experienceNetworkLatency() {        int randomLatency = random(5, 10);        for (int i = 0; i < randomLatency; i++) {            try {                Thread.sleep(100);
            } catch (InterruptedException ex) {                ex.printStackTrace();
            }
        }
    }    private void connectToServer(String server) {        System.out.print("Connecting to " + server + "... ");        experienceNetworkLatency();        System.out.print("Connected!" + "\n");
    }    private HashMap<String, Video> getRandomVideos() {        System.out.print("Downloading populars... ");        experienceNetworkLatency();        HashMap<String, Video> hmap = new HashMap<String, Video>();        hmap.put("catzzzzzzzzz", new Video("sadgahasgdas", "Catzzzz.avi"));        hmap.put("mkafksangasj", new Video("mkafksangasj", "Dog play with ball.mp4"));        hmap.put("dancesvideoo", new Video("asdfas3ffasd", "Dancing video.mpq"));        hmap.put("dlsdk5jfslaf", new Video("dlsdk5jfslaf", "Barcelona vs RealM.mov"));        hmap.put("3sdfgsd1j333", new Video("3sdfgsd1j333", "Programing lesson#1.avi"));        System.out.print("Done!" + "\n");        return hmap;
    }    private Video getSomeVideo(String videoId) {        System.out.print("Downloading video... ");        experienceNetworkLatency();        Video video = new Video(videoId, "Some video title");        System.out.print("Done!" + "\n");        return video;
    }
}

some_cool_media_library/Video.java: 视频文件

package refactoring_guru.proxy.example.some_cool_media_library;public class Video {    public String id;    public String title;    public String data;    Video(String id, String title) {        this.id = id;        this.title = title;        this.data = "Random video.";
    }
}

03proxy

proxy/YouTubeCacheProxy.java: 缓存代理

package refactoring_guru.proxy.example.proxy;import refactoring_guru.proxy.example.some_cool_media_library.ThirdPartyYouTubeClass;import refactoring_guru.proxy.example.some_cool_media_library.ThirdPartyYouTubeLib;import refactoring_guru.proxy.example.some_cool_media_library.Video;import java.util.HashMap;public class YouTubeCacheProxy implements ThirdPartyYouTubeLib {    private ThirdPartyYouTubeLib youtubeService;    private HashMap<String, Video> cachePopular = new HashMap<String, Video>();    private HashMap<String, Video> cacheAll = new HashMap<String, Video>();    public YouTubeCacheProxy() {        this.youtubeService = new ThirdPartyYouTubeClass();
    }    @Override
    public HashMap<String, Video> popularVideos() {        if (cachePopular.isEmpty()) {            cachePopular = youtubeService.popularVideos();
        } else {            System.out.println("Retrieved list from cache.");
        }        return cachePopular;
    }    @Override
    public Video getVideo(String videoId) {        Video video = cacheAll.get(videoId);        if (video == null) {            video = youtubeService.getVideo(videoId);            cacheAll.put(videoId, video);
        } else {            System.out.println("Retrieved video '" + videoId + "' from cache.");
        }        return video;
    }    public void reset() {        cachePopular.clear();        cacheAll.clear();
    }
}

04downloader

downloader/YouTubeDownloader.java: 媒体下载应用

package refactoring_guru.proxy.example.downloader;import refactoring_guru.proxy.example.some_cool_media_library.ThirdPartyYouTubeLib;import refactoring_guru.proxy.example.some_cool_media_library.Video;import java.util.HashMap;public class YouTubeDownloader {    private ThirdPartyYouTubeLib api;    public YouTubeDownloader(ThirdPartyYouTubeLib api) {        this.api = api;
    }    public void renderVideoPage(String videoId) {        Video video = api.getVideo(videoId);        System.out.println("\n-------------------------------");        System.out.println("Video page (imagine fancy HTML)");        System.out.println("ID: " + video.id);        System.out.println("Title: " + video.title);        System.out.println("Video: " + video.data);        System.out.println("-------------------------------\n");
    }    public void renderPopularVideos() {        HashMap<String, Video> list = api.popularVideos();        System.out.println("\n-------------------------------");        System.out.println("Most popular videos on YouTube (imagine fancy HTML)");        for (Video video : list.values()) {            System.out.println("ID: " + video.id + " / Title: " + video.title);
        }        System.out.println("-------------------------------\n");
    }
}

Demo.java: 初始化代码

package refactoring_guru.proxy.example;import refactoring_guru.proxy.example.downloader.YouTubeDownloader;import refactoring_guru.proxy.example.proxy.YouTubeCacheProxy;import refactoring_guru.proxy.example.some_cool_media_library.ThirdPartyYouTubeClass;public class Demo {    public static void main(String[] args) {        YouTubeDownloader naiveDownloader = new YouTubeDownloader(new ThirdPartyYouTubeClass());        YouTubeDownloader smartDownloader = new YouTubeDownloader(new YouTubeCacheProxy());        long naive = test(naiveDownloader);        long smart = test(smartDownloader);        System.out.print("Time saved by caching proxy: " + (naive - smart) + "ms");
    }    private static long test(YouTubeDownloader downloader) {        long startTime = System.currentTimeMillis();        // User behavior in our app:
        downloader.renderPopularVideos();        downloader.renderVideoPage("catzzzzzzzzz");        downloader.renderPopularVideos();        downloader.renderVideoPage("dancesvideoo");        // Users might visit the same page quite often.
        downloader.renderVideoPage("catzzzzzzzzz");        downloader.renderVideoPage("someothervid");        long estimatedTime = System.currentTimeMillis() - startTime;        System.out.print("Time elapsed: " + estimatedTime + "ms\n");        return estimatedTime;
    }
}

OutputDemo.txt: 执行结果

Connecting to http://www.youtube.com... Connected!
Downloading populars... Done!
-------------------------------
Most popular videos on YouTube (imagine fancy HTML)
ID: sadgahasgdas / Title: Catzzzz.avi
ID: asdfas3ffasd / Title: Dancing video.mpq
ID: 3sdfgsd1j333 / Title: Programing lesson#1.avi
ID: mkafksangasj / Title: Dog play with ball.mp4
ID: dlsdk5jfslaf / Title: Barcelona vs RealM.mov
-------------------------------
Connecting to http://www.youtube.com/catzzzzzzzzz... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: catzzzzzzzzz
Title: Some video title
Video: Random video.
-------------------------------
Connecting to http://www.youtube.com... Connected!
Downloading populars... Done!
-------------------------------
Most popular videos on YouTube (imagine fancy HTML)
ID: sadgahasgdas / Title: Catzzzz.avi
ID: asdfas3ffasd / Title: Dancing video.mpq
ID: 3sdfgsd1j333 / Title: Programing lesson#1.avi
ID: mkafksangasj / Title: Dog play with ball.mp4
ID: dlsdk5jfslaf / Title: Barcelona vs RealM.mov
-------------------------------
Connecting to http://www.youtube.com/dancesvideoo... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: dancesvideoo
Title: Some video title
Video: Random video.
-------------------------------
Connecting to http://www.youtube.com/catzzzzzzzzz... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: catzzzzzzzzz
Title: Some video title
Video: Random video.
-------------------------------
Connecting to http://www.youtube.com/someothervid... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: someothervid
Title: Some video title
Video: Random video.
-------------------------------
Time elapsed: 9354ms
Connecting to http://www.youtube.com... Connected!
Downloading populars... Done!
-------------------------------
Most popular videos on YouTube (imagine fancy HTML)
ID: sadgahasgdas / Title: Catzzzz.avi
ID: asdfas3ffasd / Title: Dancing video.mpq
ID: 3sdfgsd1j333 / Title: Programing lesson#1.avi
ID: mkafksangasj / Title: Dog play with ball.mp4
ID: dlsdk5jfslaf / Title: Barcelona vs RealM.mov
-------------------------------
Connecting to http://www.youtube.com/catzzzzzzzzz... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: catzzzzzzzzz
Title: Some video title
Video: Random video.
-------------------------------
Retrieved list from cache.
-------------------------------
Most popular videos on YouTube (imagine fancy HTML)
ID: sadgahasgdas / Title: Catzzzz.avi
ID: asdfas3ffasd / Title: Dancing video.mpq
ID: 3sdfgsd1j333 / Title: Programing lesson#1.avi
ID: mkafksangasj / Title: Dog play with ball.mp4
ID: dlsdk5jfslaf / Title: Barcelona vs RealM.mov
-------------------------------
Connecting to http://www.youtube.com/dancesvideoo... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: dancesvideoo
Title: Some video title
Video: Random video.
-------------------------------
Retrieved video 'catzzzzzzzzz' from cache.
-------------------------------
Video page (imagine fancy HTML)
ID: catzzzzzzzzz
Title: Some video title
Video: Random video.
-------------------------------
Connecting to http://www.youtube.com/someothervid... Connected!
Downloading video... Done!
-------------------------------
Video page (imagine fancy HTML)
ID: someothervid
Title: Some video title
Video: Random video.
-------------------------------
Time elapsed: 5875ms
Time saved by caching proxy: 3479ms
相关文章
|
9天前
|
Java
在 Java 中捕获和处理自定义异常的代码示例
本文提供了一个 Java 代码示例,展示了如何捕获和处理自定义异常。通过创建自定义异常类并使用 try-catch 语句,可以更灵活地处理程序中的错误情况。
|
24天前
|
XML 安全 Java
Java反射机制:解锁代码的无限可能
Java 反射(Reflection)是Java 的特征之一,它允许程序在运行时动态地访问和操作类的信息,包括类的属性、方法和构造函数。 反射机制能够使程序具备更大的灵活性和扩展性
35 5
Java反射机制:解锁代码的无限可能
|
20天前
|
jenkins Java 测试技术
如何使用 Jenkins 自动发布 Java 代码,通过一个电商公司后端服务的实际案例详细说明
本文介绍了如何使用 Jenkins 自动发布 Java 代码,通过一个电商公司后端服务的实际案例,详细说明了从 Jenkins 安装配置到自动构建、测试和部署的全流程。文中还提供了一个 Jenkinsfile 示例,并分享了实践经验,强调了版本控制、自动化测试等关键点的重要性。
55 3
|
25天前
|
存储 安全 Java
系统安全架构的深度解析与实践:Java代码实现
【11月更文挑战第1天】系统安全架构是保护信息系统免受各种威胁和攻击的关键。作为系统架构师,设计一套完善的系统安全架构不仅需要对各种安全威胁有深入理解,还需要熟练掌握各种安全技术和工具。
69 10
|
21天前
|
分布式计算 Java MaxCompute
ODPS MR节点跑graph连通分量计算代码报错java heap space如何解决
任务启动命令:jar -resources odps-graph-connect-family-2.0-SNAPSHOT.jar -classpath ./odps-graph-connect-family-2.0-SNAPSHOT.jar ConnectFamily 若是设置参数该如何设置
|
19天前
|
Java
Java代码解释++i和i++的五个主要区别
本文介绍了前缀递增(++i)和后缀递增(i++)的区别。两者在独立语句中无差异,但在赋值表达式中,i++ 返回原值,++i 返回新值;在复杂表达式中计算顺序不同;在循环中虽结果相同但使用方式有别。最后通过 `Counter` 类模拟了两者的内部实现原理。
Java代码解释++i和i++的五个主要区别
|
27天前
|
搜索推荐 Java 数据库连接
Java|在 IDEA 里自动生成 MyBatis 模板代码
基于 MyBatis 开发的项目,新增数据库表以后,总是需要编写对应的 Entity、Mapper 和 Service 等等 Class 的代码,这些都是重复的工作,我们可以想一些办法来自动生成这些代码。
30 6
|
27天前
|
Java
通过Java代码解释成员变量(实例变量)和局部变量的区别
本文通过一个Java示例,详细解释了成员变量(实例变量)和局部变量的区别。成员变量属于类的一部分,每个对象有独立的副本;局部变量则在方法或代码块内部声明,作用范围仅限于此。示例代码展示了如何在类中声明和使用这两种变量。
|
28天前
|
存储 Java API
优雅地使用Java Map,通过掌握其高级特性和技巧,让代码更简洁。
【10月更文挑战第19天】本文介绍了如何优雅地使用Java Map,通过掌握其高级特性和技巧,让代码更简洁。内容包括Map的初始化、使用Stream API处理Map、利用merge方法、使用ComputeIfAbsent和ComputeIfPresent,以及Map的默认方法。这些技巧不仅提高了代码的可读性和维护性,还提升了开发效率。
54 3
|
6天前
|
Java 开发者
Java多线程编程中的常见误区与最佳实践####
本文深入剖析了Java多线程编程中开发者常遇到的几个典型误区,如对`start()`与`run()`方法的混淆使用、忽视线程安全问题、错误处理未同步的共享变量等,并针对这些问题提出了具体的解决方案和最佳实践。通过实例代码对比,直观展示了正确与错误的实现方式,旨在帮助读者构建更加健壮、高效的多线程应用程序。 ####