当前位置:网站首页>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 ~
边栏推荐
- Huffman coding experiment report
- Deeply understand the mvcc mechanism of MySQL
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【SQLServer2012综合练习】
- The latest version of lottery blind box operation version
- 并网-低电压穿越与孤岛并存分析
- Express abstract classes and methods
- C graphical tutorial (Fourth Edition)_ Chapter 15 interface: interfacesamplep271
- Quickly learn member inner classes and local inner classes
- Export the entire Oracle Database
- 【習題五】【數據庫原理】
猜你喜欢
[ArcGIS user defined script tool] vector file generates expanded rectangular face elements
基于同步坐标变换的谐波电流检测
【R】【密度聚类、层次聚类、期望最大化聚类】
Analysis of a music player Login Protocol
【综合题】【数据库原理】
ncnn神經網絡計算框架在香柳丁派OrangePi 3 LTS開發板中的使用介紹
剑指 Offer 12. 矩阵中的路径
Application of ncnn neural network computing framework in orange school orangepi 3 lts development board
Powerful avatar making artifact wechat applet
01 three solutions to knapsack problem (greedy dynamic programming branch gauge)
随机推荐
【Colab】【使用外部数据的7种方法】
【数据库原理及应用教程(第4版|微课版)陈志泊】【第六章习题】
Gan totem column bridgeless boost PFC (single phase) seven PFC duty cycle feedforward
Glide question you cannot start a load for a destroyed activity
[exercise 5] [Database Principle]
【習題七】【數據庫原理】
Cache penetration and bloom filter
【数据库原理及应用教程(第4版|微课版)陈志泊】【SQLServer2012综合练习】
Node. Js: use of express + MySQL
[combinatorics] permutation and combination (multiple set permutation | multiple set full permutation | multiple set incomplete permutation all elements have a repetition greater than the permutation
Node.js: express + MySQL的使用
如何在微信小程序中获取用户位置?
Brief introduction to mvcc
GaN图腾柱无桥 Boost PFC(单相)七-PFC占空比前馈
Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
自抗扰控制器七-二阶 LADRC-PLL 结构设计
[Exercice 5] [principe de la base de données]
OpenHarmony应用开发之ETS开发方式中的Image组件
Analysis of a music player Login Protocol
01 three solutions to knapsack problem (greedy dynamic programming branch gauge)