官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 松阳县| 长兴县| 达尔| 苍山县| 正镶白旗| 金溪县| 双桥区| 五指山市| 阳西县| 松原市| 香河县| 称多县| 明溪县| 定襄县| 黄陵县| 义乌市| 阳春市| 高尔夫| 古蔺县| 河津市| 攀枝花市| 宝山区| 花垣县| 景东| 汕头市| 定西市| 新巴尔虎右旗| 九龙县| 和平区| 紫金县| 祁东县| 苏尼特右旗| 铜鼓县| 新昌县| 壶关县| 嵊州市| 若羌县| 米泉市| 噶尔县| 灵武市| 楚雄市|