单例方法

    单例方法

    The behavior of an instance is determined by its class, but there may be times we know that a particular instance should have special behavior.

    一个实例的行为是由它所属的类决定的,但是我们也有可能知道,特定的实例有自己特定的行为。

    In most languages, we must go to the trouble of defining another class, which would then only be instantiated once.

    In ruby we can give any object its own methods.

    Ruby中,我们可以给任何对象它自己的方法。

    In this example, test1 and test2 belong to same class, but test2 has been given a redefined size method and so they behave differently. A method given only to a single object is called a singleton method.

    在这个示例中,test1和test2都属于同一个类,但是test2重定义了方法,因此它们有不同的行为。只属于一个对象的方法被称为单例方法

    单例方法经常用于图形用户界面(GUI)的元素,当不同的按钮被按下时,需要采取不同的行动。

    Singleton methods are not unique to ruby, as they appear in CLOS, Dylan, etc. Also, some languages, for example, Self and NewtonScript, have singleton methods only. These are sometimes called prototype-based languages.

    单例方法并不是Ruby独有的,它出现于CLOSDylan等,同样,也出现于许多语言中,例如,SelfNewtonScript只有单例方法。它们有时被称为基于原型的语言


    下一章 模块