實體的行為取決於其類,但很多時候我們知道一個特定的實體需要特定的行為.在很多語言里,我們必須陷入另外再定義一個類的麻煩里,即使它只是用來接著實體化一次.在Ruby里,我們可以賦予任何對象屬於其自身的方法.
ruby> class SingletonTest
| def size
| print "25\n"
| end
| end
nil
ruby> test1 = SingletonTest.new
#<SingletonTest:0xbc468>
ruby> test2 = SingletonTest.new
#<SingletonTest:0xbae20>
ruby> def test2.size
| print "10\n"
| end
nil
ruby> test1.size
25
nil
ruby> test2.size
10
nil
在這個例子里,test1和test2屬於相同的類,但test2已被賦給一個重載的size方法,因而他們有不同的行為.一個僅屬於某個對象的方法叫做單態方法.
單態方法常常用於圖形用戶界面(GUI)的元素的設計,在那裡當不同的按鈕被壓下時將會激發不同的事件.
單態方法並非Ruby的專利,它也出現在CLOS,Dylan等語言中.同時,有些語言,比如,Self和NewtonScript僅有單態方法.他們有時被稱作基於範例(prototype-based)語言.
ruby> class SingletonTest
| def size
| print "25\n"
| end
| end
nil
ruby> test1 = SingletonTest.new
#<SingletonTest:0xbc468>
ruby> test2 = SingletonTest.new
#<SingletonTest:0xbae20>
ruby> def test2.size
| print "10\n"
| end
nil
ruby> test1.size
25
nil
ruby> test2.size
10
nil
在這個例子里,test1和test2屬於相同的類,但test2已被賦給一個重載的size方法,因而他們有不同的行為.一個僅屬於某個對象的方法叫做單態方法.
單態方法常常用於圖形用戶界面(GUI)的元素的設計,在那裡當不同的按鈕被壓下時將會激發不同的事件.
單態方法並非Ruby的專利,它也出現在CLOS,Dylan等語言中.同時,有些語言,比如,Self和NewtonScript僅有單態方法.他們有時被稱作基於範例(prototype-based)語言.