Ruby Single State Method analysis _ruby Special topic

Source: Internet
Author: User
The behavior of an entity depends on its class, but many times we know that a particular entity requires specific behavior. In many languages, we have to get into the trouble of defining another class, even if it's just going to be materialized once. In Ruby, we can give any object the way it belongs to itself.

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


In this example, Test1 and test2 belong to the same class, but test2 have been assigned to an overloaded size method, so they behave differently. A method that belongs to only one object is called a single state method.

A single state method is often used in the design of elements of a graphical user interface (GUI), where different events are fired when different buttons are pressed.

The single State method is not patented by Ruby, and it also appears in languages such as Clos,dylan. At the same time, some languages, such as self and newtonscript, have only a single state method. They are sometimes referred to as case-based (prototype-based) languages.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.