074: Kotlin의 프록시 패턴: 다른 개체에 대리자 또는 자리 표시자 제공Korean version of this document is available
074: Kotlin のプロキシ パターン: 別のオブジェクトのサロゲートまたはプレースホルダーを提供するJapanese version of this document is available
074:Kotlin 中的代理模式:为另一个对象提供代理项或占位符Chinese Simplified version of this document is available
Add a link to the original article in the "Resources" section.
The Proxy Pattern is a software design pattern that provides a surrogate or placeholder object for another. In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural patterns.
There are four types of proxy patterns:
In this article, we will focus on the Virtual Proxy pattern.
A virtual proxy is an object that represents another object. The real object is only created when it is needed. For example, an image that is loading from a remote server. The image is represented by a proxy object. The proxy object handles the request for the image. When the image is loaded, the proxy object replaces itself with the real image object.
A virtual proxy can be used to:
We will use the following example to demonstrate the Virtual Proxy pattern. We have a User class that represents a user. The User class has a name and an avatar. The avatar is an image. We will use a virtual proxy to represent the avatar image.
class User(val name: String, val avatar: Image)
The Image class represents an image. The Image class has a width and a height.
class Image(val width: Int, val height: Int)
The ImageProxy class is a proxy for the Image class. The ImageProxy class has a reference to the Image class. The ImageProxy class also has a loading flag. The loading flag is used to track whether the Image class is loading or not.
class ImageProxy(val image: Image) {
val loading = false
}
The loadImage() function is used to load the Image class. The loadImage() function takes an image URL and a callback function. The callback function is called when the image is loaded.
fun loadImage(imageUrl: String, callback: (Image) -> Unit) {
// TODO: load image from URL
}
The main() function creates a User object with an ImageProxy object. The ImageProxy object represents the avatar image. The loadImage() function is used to load the avatar image. When the image is loaded, the ImageProxy object is replaced with the Image object.
fun main() {
val user = User("Alice", ImageProxy(null))
loadImage("avatar.jpg") { image ->
user.avatar = image
}
}
The Virtual Proxy pattern should be used when:
The Virtual Proxy pattern has the following advantages:
The Virtual Proxy pattern has the following disadvantages: