Java

Usage examples: While the Proxy pattern isn’t a frequent guest in most Java applications, it’s still very handy in some special cases. It’s irreplaceable when you want to add some additional behaviors to an object of some existing class without changing the client code.

Some examples of proxies in standard Java libraries:

Identification: Proxies delegate all of the real work to some other object. Each proxy method should, in the end, refer to a service object unless the proxy is a subclass of a service.

Caching proxy

In this example, the Proxy pattern helps to implement the lazy initialization and caching to an inefficient 3rd-party YouTube integration library.

Proxy is invaluable when you have to add some additional behaviors to a class which code you can’t change.

some_cool_media_library

some_cool_media_library/ThirdPartyYouTubeLib.java: Remote service interface

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: Remote service implementation

some_cool_media_library/Video.java: Video file

proxy

proxy/YouTubeCacheProxy.java: Caching proxy

downloader

downloader/YouTubeDownloader.java: Media downloader app

Demo.java: Initialization code

OutputDemo.txt: Execution result

Last updated