Cover by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Chapter 11. The Proxy Pattern: Controlling Object Access

image with no caption

Ever play good cop, bad cop? You’re the good cop and you provide all your services in a nice and friendly manner, but you don’t want everyone asking you for services, so you have the bad cop control access to you. That’s what proxies do: control and manage access. As you’re going to see, there are lots of ways in which proxies stand in for the objects they proxy. Proxies have been known to haul entire method calls over the Internet for their proxied objects; they’ve also been known to patiently stand in the place for some pretty lazy objects.

image with no caption

Sounds easy enough. If you remember, we’ve already got methods in the gumball machine code for getting the count of gumballs (getCount()), and getting the current state of the machine (getState()).

All we need to do is create a report that can be printed out and sent back to the CEO. Hmmm, we should probably add a location field to each gumball machine as well; that way the CEO can keep the machines straight.

Let’s just jump in and code this. We’ll impress the CEO with a very fast turnaround.

Coding the Monitor

Let’s start by adding support to the GumballMachine class so that it can handle locations:

Now let’s create another class, GumballMonitor, that retrieves the machine’s location, inventory ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required