- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 291字
- 2021-06-24 14:13:34
Class delegation
You might have already heard about the delegation pattern or at least used it without even knowing it had a name. It allows a type to forward one or more of its method calls to a different type. Therefore, you need two types to achieve this—the delegate and the delegator.
This might sound like it's a proxy pattern, but it isn't. A proxy pattern is meant to provide a placeholder for an instance to get full control while accessing it. Let's say you are writing a UI framework and you start where your abstraction is UIElement. Each of the components defines a getHeight and getWidth. Consider the following diagram:

The following code block shows you the unified modeling language (UML) translated into Kotlin. We defined the UIElement interface with both the Panel and Rectangle classes inheriting the following:
interface UIElement { fun getHeight(): Int fun getWidth(): Int } class Rectangle(val x1: Int, val x2: Int, val y1: Int, val y2: Int) : UIElement { override fun getHeight() = y2 - y1 override fun getWidth() = x2 - x1 } class Panel(val rectangle: Rectangle) : UIElement by rectangle val panel = Panel(Rectangle(10,100,30,100)) println("Panel height:"+panel.getHeight()) println("Panel witdh:" + panel.getWidth())
You have probably noticed the by keyword in the Panel class definition. It's basically a hint for the compiler to do the work for you—forwarding the calls for the methods exposed by the UIElement interface to the underlying Rectangle object.
Through this pattern, you replace inheritance with composition. You should always favor composition over inheritance for the sake of simplicity, reducing type coupling, and flexibility. Using this approach, you can choose and swap the type you put in the delegate position based on various requirements.
- Unity 2020 By Example
- Learning Cython Programming(Second Edition)
- PyTorch自動(dòng)駕駛視覺感知算法實(shí)戰(zhàn)
- SQL Server 2012數(shù)據(jù)庫技術(shù)及應(yīng)用(微課版·第5版)
- PyTorch自然語言處理入門與實(shí)戰(zhàn)
- 實(shí)戰(zhàn)低代碼
- Effective Python Penetration Testing
- Mastering Apache Spark 2.x(Second Edition)
- 微信小程序入門指南
- NoSQL數(shù)據(jù)庫原理
- C++寶典
- OpenCV 3計(jì)算機(jī)視覺:Python語言實(shí)現(xiàn)(原書第2版)
- C語言程序設(shè)計(jì)與應(yīng)用實(shí)驗(yàn)指導(dǎo)書(第2版)
- Tkinter GUI Application Development Blueprints
- 嵌入式Linux與物聯(lián)網(wǎng)軟件開發(fā):C語言內(nèi)核深度解析