授权模式的目的是什么? [英] What is the purpose of a delegation pattern?

查看:325
本文介绍了授权模式的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过源代码 SensorManager ,发现当您注册一个 SensorEventListener 传感器管理器将侦听器的控制权传递给一个 ListenerDelegate



我只是把它作为一个例子。我阅读了关于委托编程的维基百科文章,但我仍然不确定其目的。为什么会使用委托?它如何帮助程序的控制流程?使用(或不)一个的缺点是什么?在听众中使用最实际吗?



编辑: ListenerDelegate 在第487行,相关方法

解决方案

代表团不完全是GoF书中使用的意义上的设计模式。它在许多情况下很有用,并且是您之前/之后执行其他操作的其他模式的基础




  • 委托(这是Decorator模式,但是基于委派)。例如, Collections.synchronizedList(..)创建一个新的集合,委托给原来的集合,但其方法已同步。

  • 当您有不兼容的接口,并希望适应一个(适配器模式)。您将获得原始对象并从符合所需界面的方法委托给它。例如,有 EnumerationIterator 类,可以将枚举适用于 Iterator 接口。该类有一个 hasNext()方法,委托给 enumeration.hasMoreElements()

  • 当您希望隐藏课堂用户的一些复杂性时,您可以使用委派给不同实际工作人员的方法。例如, Car 可以具有 start() openWindow() brake(),但是这些方法中的每一个实际上都将委托给引擎,el.windows和制动系统(另见这个

      I was looking through the source to SensorManager in Android and found that when you register a SensorEventListener the SensorManager passes control of the listener to a ListenerDelegate.

      I only bring this up as an example. I read the Wikipedia article on delegate programming but I am still not sure of its purpose. Why would one use a 'delegate'? How does it help the control flow of a program? What are the disadvantages of using (or not) one? Is it most practical for use with listeners?

      Edit: ListenerDelegate is on line 487 and the methods in question are around line 1054.

      解决方案

      Delegation is not exactly a 'design pattern' in the sense used in the GoF book. It is useful in a number of scenarios, and is a base for other patterns

      • when you want to perform some additional actions before/after you delegate (that's the Decorator pattern, but it's based on delegation). For example, Collections.synchronizedList(..) creates a new collection that delegates to the original one, but has its methods synchronized.
      • when you have incompatible interfaces and you want to adapt one to the other (the adapter pattern). You get the original object and delegate to it from methods that conform to the desired interface. For example, there's the EnumerationIterator class, that adapts enumerations to the Iterator interface. The class has a hasNext() method which delegates to enumeration.hasMoreElements()
      • when you want to hide some complexity from the user of your class, you can have methods that delegate to different actual workers. For example, a Car can have start(), openWindow() and brake(), but each of these methods will actually delegate to the engine, el.windows and braking system (see also this)

      这篇关于授权模式的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆