Leasing an Object Using a Revocable Proxy

Learn about the interesting concept of revocable proxy with examples.

You’ve learned to create proxies and write traps; let’s move on to applying this knowledge. Our target is method synthesis, but let’s explore one other benefit of proxies: the ability to lease an object.

Suppose we want to limit the lifetime of an object. A function that creates an object with new may use it as long as it wants, as long as the instance reference is in the scope. If you want to return an object to a caller but withdraw or revoke access to that object either after some time or when some condition is met, use a revocable proxy.

Creating a revocable proxy

Here’s a counterFactory() function that creates an instance of a Counter class but returns a revocable proxy instead of the original object.

Get hands-on with 1200+ tech skills courses.