November 26, 20269 minutes
A playlist of two hundred songs stays blank for twenty seconds. Learn how a Proxy that looks exactly like the real object decides when, whether and where a call gets through, and how it differs from Decorator and Adapter.
Your music app opens a playlist of two hundred songs. And the screen stays blank for twenty seconds. The user wanted to hear one song. So where did the time go? Every track loads its whole audio file the moment it’s created: a tenth of a second each, two hundred times over. Why load two hundred songs to play one? There’s a pattern for this, and it’s called the Proxy.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
The playlist screen creates one AudioTrack per song, and each constructor reads the whole file.
0.1 s × 200 = 20 s before the first title shows up. Creating the real thing up front costs time the
user never asked to spend.
Picture calling a busy director’s office. You dial his number, and his assistant picks up. Ask for his schedule, and she answers herself. Ask to talk to him, and she checks you’re on his list first. If he’s on a plane, she takes the call and connects you when he lands. And she writes every call in the log. The whole time, you dialed the same number. You never had to know who was screening the call.
In code, that number is the subject, the interface. The director is the real subject. The assistant is the proxy. And you, the caller, are the client.
Here’s the interface. A track has a title, and it can play.
public interface Track {
String title();
void play();
}The real track, audio track, loads the whole file in its constructor. That makes play instant, because the bytes are already there.
public class AudioTrack implements Track {
private final String title;
private final byte[] audio;
public AudioTrack(String title, Path file) {
this.title = title;
this.audio = AudioFile.load(file); // slow
}
public String title() { return title; }
public void play() { Speaker.play(audio); }
}And the playlist screen builds one track for every song in the library.
for (Song song : library.songs()) {
playlist.add(new AudioTrack(song.title(), song.file()));
}For a ten song album, that’s fair. It’s simple, and no song ever pauses when you press play.
(AudioFile, Speaker, Song and library are this example’s own helpers; their bodies don’t
matter here.)
But two hundred songs means two hundred loads before the screen appears. And the playlist only needs the titles.
The tempting fix is to make the track lazy inside. Keep the file, and load it on the first play.
Fair enough. Then product asks for premium only songs, and a log of every play. Each rule lands in
the same play method:
public void play() {
if (!user.isPremium()) throw new SecurityException();
if (audio == null) audio = AudioFile.load(file);
playLog.record(title);
Speaker.play(audio);
}Look at what’s left. Only the last line is about playing music. The rest decides when, who, and what gets written down. And every screen that creates tracks now has to know about users, and about the play log. It’s the director answering his own phone, checking his own guest list, and keeping his own call log.
Here’s the shift. When you reach an object, whether you may, and where it lives are not that
object’s job. So put them in a stand-in. It implements the same Track interface, and it holds the
real track, or knows how to get it. The playlist holds a Track, and it can’t tell the difference.
The real track goes back to just playing.
The Gang of Four put it like this: “Provide a surrogate or placeholder for another object to control access to it.”
Look the same. Guard the way in.
Here’s the lazy track. It implements Track, and it keeps the title, the file path, and an empty
slot for the real one. title() answers from its own field. No loading at all. play() checks the
slot. On the first call, it creates the real audio track. After that, every call goes straight to
it.
public class LazyTrack implements Track {
private final String title;
private final Path file;
private Track real;
public LazyTrack(String title, Path file) {
this.title = title;
this.file = file;
}
public String title() { return title; } // no loading
public void play() {
if (real == null) {
real = new AudioTrack(title, file);
}
real.play();
}
}The playlist changes a single word: LazyTrack, instead of AudioTrack.
playlist.add(new LazyTrack(song.title(), song.file()));Now the screen opens at once, with every title. Play the third song, and only that song loads. Play it again, and nothing loads at all.
And AudioTrack didn’t change at all. It still loads, and it still plays. The laziness lives in
one small class beside it.
The same shape does four different jobs:
| Kind | What it controls | In this lesson |
|---|---|---|
| Virtual proxy | creates the expensive object on demand | LazyTrack |
| Protection proxy | checks rights before passing a call on | PremiumTrack |
| Remote proxy | stands in for an object that lives somewhere else | a song on a server |
| Smart reference | a little housekeeping on every access: caching an answer, counting uses, logging | a play counter |
Here’s a protection proxy. Premium track holds any track, and checks the user before it lets play through.
public class PremiumTrack implements Track {
private final Track real;
private final User user;
public PremiumTrack(Track real, User user) {
this.real = real;
this.user = user;
}
public String title() { return real.title(); }
public void play() {
if (!user.isPremium()) {
throw new SecurityException("premium only");
}
real.play();
}
}Each rule is its own small class now. You can test the premium check without a single audio file. And proxies stack. Put the premium check in front of a lazy track, and a free user never loads a single byte:
Track track = new PremiumTrack(new LazyTrack(title, file), user);Hibernate uses this every day. Its getReference method gives you a person without loading the
person. The example is straight from the Hibernate user guide:
Book book = new Book();
book.setAuthor(entityManager.getReference(Person.class, personId));What you get back is a proxy, generated at run time, that looks like a Person. Set it as the
book’s author, and no query runs. Hibernate loads the row only when you use its data. And if the row
doesn’t exist, the error waits until that first use. In the guide’s words, “an exception will be
thrown later if the given entity does not refer to actual database state when the application
attempts to use the returned proxy in any way that requires access to its data.” (Unless the entity
class is final, Hibernate’s proxy extends the entity class, which is why the guide asks for
non-final entities.)
The JDK can also build a proxy for any interface while your program runs. Proxy.newProxyInstance
takes the interfaces and one handler. Every call on that proxy goes through the handler. This one
prints the method’s name, then passes the call on to the real track:
Track logged = (Track) Proxy.newProxyInstance(
Track.class.getClassLoader(),
new Class<?>[] { Track.class },
(proxy, method, args) -> {
System.out.println("call: " + method.getName());
return method.invoke(real, args);
});Calling logged.title() and then logged.play() prints call: title and call: play. The javadoc
describes it the same way: a proxy class “is a class created at runtime that implements a specified
list of interfaces”, and each call “will be dispatched to the invoke method of the instance’s
invocation handler”. It only works for interfaces, not classes.
Now a common mix up: a proxy is just a decorator. They do look alike. Same interface, and both hold the real object. The difference is the purpose. A decorator adds one more job, like making every track louder. A proxy decides when, whether, or where a call gets through.
The Gang of Four even say “a protection proxy might be implemented exactly like a decorator.” So read the intent, not the shape. The Decorator lesson puts it as “Same interface, one more job.”
An adapter is different again. It changes the interface, so the caller sees a new shape. A proxy never does (see Adapter: “Change the shape, not the job.”). An assistant who rewrites the director’s answers has stopped screening the calls. She’s editing them.
| Interface | Purpose | |
|---|---|---|
| Proxy | same | controls access: when, whether, where |
| Decorator | same | adds a responsibility |
| Adapter | different | makes a class fit an interface you have |
| Facade | new, simpler | one front for many classes |
When should you skip it? A proxy adds a level of indirection. If the object is cheap to make, you don’t need one. Lazy loading moves the delay to the first play. The list opens fast, but that first song takes its tenth of a second. Failures show up late, too. A missing file, or a missing row, surfaces at first use, far from where the object was made.
And the null check we wrote isn’t safe across threads. Two threads can load the same song twice (the Singleton lesson walks through the same race and its fixes). And if the caller needs to know it’s talking to a stand-in, say to show a loading spinner, a proxy that pretends hides too much.
Checklist:
Look the same. Guard the way in.
Related lessons: Decorator, Adapter, Facade, Singleton.
java.lang.reflect.Proxy javadoc.