当前位置:网站首页>Kotlin - improved decorator mode
Kotlin - improved decorator mode
2022-07-03 13:03:00 【GitLqr】
Welcome to WeChat official account. :FSA Whole stack operation
- Kotlin - Improved factory mode
- Kotlin - Improved builder model
- Kotlin - Improved observer mode
- Kotlin - Improved strategy model
- Kotlin - Improved iterator mode
- Kotlin - Improve the responsibility chain model
- Kotlin - Improved decorator mode
One 、 Preface
- Decorator mode
- effect : Without having to change the original class file and use inheritance , Dynamically extend the function of an object .
- The essence : This pattern creates a wrapper object , To wrap real objects .
- Core operations :
- Create a decoration class , Contains an instance of the decorated class
- The decorated class overrides all the methods of the decorated class
- Extend the functions that need to be enhanced in the decoration class
Two 、 Use decorator mode
- Example : Gun parts
- a key : Decorator design ( Implement the same interface as the decorated class , The constructor receives the interface instance object of the decorated class )
Big shooting games like Jedi survival , The gun system inside is very complicated , There are many kinds of guns , And almost every kind of gun can be equipped with various parts , Such as muffler 、 Eightfold mirror or something , The functions of the components vary , Some can increase firepower , Some can improve accuracy , wait , Now let's simply design the gun system , There are many kinds of guns , Therefore, it is necessary to define an interface to describe the capabilities of guns , For subsequent expansion of various new guns :
/** * Gun interface * * @author GitLqr */
interface Gun {
/** * aggressivity */
fun attack(): Float
/** * The noise */
fun noise(): Float
/** * Date of manufacture */
fun prodDate(): String
}
/** * Ump9 * * @author GitLqr */
class Ump9Gun : Gun {
override fun attack() = 100f
override fun noise() = 20f
override fun prodDate() = "2020-02-18"
}
It's only realized here Ump9 This type of gun , It can also be extended as needed , Now think about the design of gun parts ? stay Java in , There are two options for extending a class behavior :
- Design a subclass that inherits it
- Use decorator mode to decorate this class
Is it appropriate to design gun parts by inheritance ? Obviously not , Because one part can be assembled on more than one gun , So inheritance excludes . Another way , Using decorator mode has a big advantage , Lies in conformity with “ Combination over inheritance ” Design principles , We know , Components can be combined with any gun , Show , Using decorator mode to design gun parts is a good choice :
/** * Gun parts * * @author GitLqr */
abstract class GunPart(protected val gun: Gun) : Gun
/** * Muffler * * @author GitLqr */
class Muffler(gun: Gun) : GunPart(gun) {
override fun attack() = gun.attack() - 5
override fun noise() = 0f
override fun prodDate() = gun.prodDate()
}
/** * Incendiary Ammo * * @author GitLqr */
class FireBullet(gun: Gun) : GunPart(gun) {
override fun attack() = gun.attack() + 200
override fun noise() = gun.noise()
override fun prodDate() = gun.prodDate()
}
When programming , Decorator ( parts ) Will reference the decorated instance ( gun ), And implement all interfaces of the decorated instance , Then add the enhanced logic to the interface method that needs to be enhanced . Because gun parts GunPart receive Gun Type construction parameters , And it's also Gun Implementation class of interface , therefore , Can make a variety of gun parts GunPart Nested decorated gun instances :
// Use
var ump9: Gun = Ump9Gun()
println(" Before assembly :ump9 aggressivity ${
ump9.attack()}, The noise ${
ump9.noise()}")
ump9 = Muffler(FireBullet(ump9)) // Assembled Incendiary Ammo 、 Muffler Of ump9
println(" After assembly :ump9 aggressivity ${
ump9.attack()}, The noise ${
ump9.noise()}")
// Output
Before assembly :ump9 aggressivity 100.0, The noise 20.0
After assembly :ump9 aggressivity 295.0, The noise 0.0
3、 ... and 、 Improved decorator mode
- Example : Gun parts
- a key : Class delegation (
bykeyword )
In the example above , Decorator pattern can solve the problem of instance combination , But the code still seems to be slow , Because you need to override all decorating object methods , So there may be a lot of boilerplate code . such as FireBullet Only decorative enhancements attack() Method , and noise()、prodDate() No modification is made , But we have to rewrite these two methods .Kotlin Class delegate feature in , utilize by keyword , Delegate all the methods of the decorated class to a decorated class object , Then just overwrite the decoration method :
/** * Gun parts * * @author GitLqr */
abstract class GunPart(protected val gun: Gun) : Gun by gun
/** * Muffler * * @author GitLqr */
class Muffler(gun: Gun) : GunPart(gun) {
override fun attack() = gun.attack() - 5
override fun noise() = 0f
}
/** * Incendiary Ammo * * @author GitLqr */
class FireBullet(gun: Gun) : GunPart(gun) {
override fun attack() = gun.attack() + 200
}
You can see , After using class delegates , Decoration FireBullet There is no need to rewrite the boilerplate code in , This reduces the amount of code .
If the article helps you , Please pay close attention to my WeChat official account :FSA Whole stack operation , It's going to be the biggest incentive for me . The official account is not only public. Android technology , also iOS, Python Wait for the article , There may be some skills and knowledge you want to know ~
边栏推荐
- 社交社区论坛APP超高颜值UI界面
- 【習題五】【數據庫原理】
- [exercice 7] [principe de la base de données]
- Glide question you cannot start a load for a destroyed activity
- How to convert a decimal number to binary in swift
- 【数据挖掘复习题】
- 并网-低电压穿越与孤岛并存分析
- Gan totem column bridgeless boost PFC (single phase) seven PFC duty cycle feedforward
- 【综合题】【数据库原理】
- CVPR 2022 图像恢复论文
猜你喜欢

Seven second order ladrc-pll structure design of active disturbance rejection controller

如何在微信小程序中获取用户位置?

Grid connection - Analysis of low voltage ride through and island coexistence

The latest version of lottery blind box operation version

Image component in ETS development mode of openharmony application development

【数据库原理及应用教程(第4版|微课版)陈志泊】【第四章习题】

自抗扰控制器七-二阶 LADRC-PLL 结构设计

【数据库原理复习题】

When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution

(latest version) WiFi distribution multi format + installation framework
随机推荐
Sword finger offer 17 Print from 1 to the maximum n digits
Sword finger offer 12 Path in matrix
Swift Error Handling
studio All flavors must now belong to a named flavor dimension. Learn more
OpenHarmony应用开发之ETS开发方式中的Image组件
【数据挖掘复习题】
[exercise 6] [Database Principle]
【数据库原理及应用教程(第4版|微课版)陈志泊】【第七章习题】
【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
(latest version) WiFi distribution multi format + installation framework
Seven second order ladrc-pll structure design of active disturbance rejection controller
Redhat5 installing socket5 proxy server
Everything comes to him who waits
关于CPU缓冲行的理解
Leetcode234 palindrome linked list
ncnn神经网络计算框架在香橙派OrangePi 3 LTS开发板中的使用介绍
[exercise 5] [Database Principle]
[network counting] Chapter 3 data link layer (2) flow control and reliable transmission, stop waiting protocol, backward n frame protocol (GBN), selective retransmission protocol (SR)
高效能人士的七个习惯
The foreground uses RSA asymmetric security to encrypt user information