当前位置:网站首页>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 ~
边栏推荐
- 2022-01-27 research on the minimum number of redis partitions
- 初入职场,如何快速脱颖而出?
- 有限状态机FSM
- alright alright alright
- C graphical tutorial (Fourth Edition)_ Chapter 15 interface: interfacesamplep268
- ncnn神經網絡計算框架在香柳丁派OrangePi 3 LTS開發板中的使用介紹
- Glide question you cannot start a load for a destroyed activity
- SLF4J 日志门面
- Integer case study of packaging
- context. Getexternalfilesdir() is compared with the returned path
猜你喜欢

Deeply understand the mvcc mechanism of MySQL

对业务的一些思考

强大的头像制作神器微信小程序

Integer case study of packaging

Swift bit operation exercise

低代码平台国际化多语言(i18n)技术方案
![[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number](/img/9d/6118b699c0d90810638f9b08d4f80a.jpg)
[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number

How to get user location in wechat applet?

【数据库原理复习题】

Analysis of a music player Login Protocol
随机推荐
Xctf mobile--app2 problem solving
Redhat5 installing socket5 proxy server
Node. Js: use of express + MySQL
最新版盲盒商城thinkphp+uniapp
[exercise 6] [Database Principle]
SQL learning notes (I)
Dojo tutorials:getting started with deferrals source code and example execution summary
4. 无线体内纳米网:电磁传播模型和传感器部署要点
sitesCMS v3.1.0发布,上线微信小程序
Sword finger offer 17 Print from 1 to the maximum n digits
Glide 4.6.1 API initial
2022-02-10 introduction to the design of incluxdb storage engine TSM
[judgment question] [short answer question] [Database Principle]
studio All flavors must now belong to a named flavor dimension. Learn more
【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
基于同步坐标变换的谐波电流检测
C graphical tutorial (Fourth Edition)_ Chapter 17 generic: genericsamplep315
C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - cases without asynchronous
C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - using asynchronous
Cache penetration and bloom filter