A replacement

When we discussed Creational Patterns, we already discussed the idea of expensive objects. For example, an object that accesses network resources, or takes a lot of time to create.

We at Funny Cat App (name invented by the canary Michael; remember him from the Flyweight pattern?) provide our users with funny cat images on a daily basis. On our homepage and mobile application, each user sees a lot of thumbnails of funny cats. When he clicks or touches any of those images, it expands to its full-screen glory. 

But fetching cat images over the network is very expensive, and it consumes a lot of memory, especially if those are images of cats that tend to indulge themselves in a second dessert after dinner. So, what we would like to do is to have a smart object, something that manages itself.

When the first user access this image, it will be fetched over the network. No way of avoiding that. 

But when it's being accessed for the second time, by this or some other user, we would like to avoid going over the network again, and instead return the result that was cached. That's the misbehaving part, as we described. Instead of the expected behavior of going over the network each time, we're being a bit lazy, and returning the result that we already prepared. It's a bit like going into a cheap diner, ordering a hamburger, and getting it after only two minutes, but cold. Well, that's because someone else hated onions and returned it to the kitchen a while ago. True story.

That sounds like a lot of logic. But, as you've probably guessed, especially after meeting the Decorator design pattern, Kotlin can perform miracles by reducing the amount of boilerplate code you need to write to achieve your goals:

data class CatImage(private val thumbnailUrl: String, 
private val
url: String) {
val image: java.io.File by lazy {
// Actual fetch goes here
}
}

As you may notice, we use the by keyword to delegate initialization of this field to a standard function called lazy.

The first call to image will execute a block of our code and save its results into the image property.

Sometimes, the Proxy design pattern is divided into three sub-patterns:

  • Virtual proxy: Lazily caches the result
  • Remote proxy: Issues a call to the remote resource
  • Protection or access control proxy: denies access to unauthorized parties

Depending on your views, you can regard our example as either a virtual proxy or a combination of virtual and remote proxies.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.198.174