当前位置:网站首页>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 (
by
keyword )
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 ~
边栏推荐
- 十條職場規則
- 【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
- Kotlin notes - popular knowledge points asterisk (*)
- Application of ncnn neural network computing framework in orange school orangepi 3 lts development board
- 自抗扰控制器七-二阶 LADRC-PLL 结构设计
- Dojo tutorials:getting started with deferrals source code and example execution summary
- I'm too lazy to write more than one character
- Create a dojo progress bar programmatically: Dojo ProgressBar
- Grid connection - Analysis of low voltage ride through and island coexistence
- OpenHarmony应用开发之ETS开发方式中的Image组件
猜你喜欢
Idea full text search shortcut ctr+shift+f failure problem
OpenHarmony应用开发之ETS开发方式中的Image组件
[comprehensive question] [Database Principle]
强大的头像制作神器微信小程序
Method overloading and rewriting
低代码平台国际化多语言(i18n)技术方案
Powerful avatar making artifact wechat applet
【综合题】【数据库原理】
01 three solutions to knapsack problem (greedy dynamic programming branch gauge)
我的创作纪念日:五周年
随机推荐
电压环对 PFC 系统性能影响分析
基于同步坐标变换的谐波电流检测
GaN图腾柱无桥 Boost PFC(单相)七-PFC占空比前馈
【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
基于Linu开发的项目视频
Attack and defense world mobile--ph0en1x-100
2022-01-27 use liquibase to manage MySQL execution version
Analysis of a music player Login Protocol
【習題五】【數據庫原理】
An example of newtonjason
自抗扰控制器七-二阶 LADRC-PLL 结构设计
Application of ncnn neural network computing framework in orange school orangepi 3 lts development board
Xctf mobile--app2 problem solving
Sword finger offer 14- I. cut rope
强大的头像制作神器微信小程序
Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
Glide question you cannot start a load for a destroyed activity
ORM use of node -serialize
Xctf mobile--app3 problem solving
2022-02-09 survey of incluxdb cluster