Chapter 11. Controlling Object Access: The Proxy Pattern

Images

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 for some pretty lazy objects.

Images

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, ...

Get Head First Design Patterns, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.