Reputation: 1636
To the best of my knowledge, these are how the singleton classes are used in Java and Ruby
To sum up, singleton classes in ruby are the same as those in java except for the facility to hold custom methods. Have I understood it right or am I missing something here ?
Upvotes: 3
Views: 430
Reputation: 22325
You are technically correct, but I think there's a big difference that you don't mention.
In Java, a singleton class is something that you implement. In other words, it's a design pattern which is generally only used in specific cases (see the link for examples). The singleton pattern is also widely considered to be a bad idea, so singleton classes are best avoided in Java.
In Ruby, a singleton class is something implicit to every Object. It's always there, but is only utilized when the programmer wants to make class-level changes on a per-instance basis (like adding methods). It is similar to the Java case only in the sense that it can have only one instance. Singleton classes in Ruby are very handy and can be very powerful when used with metaprogramming.
Of course you can also implement the singleton pattern in Ruby, but when a Rubyist says "singleton class" they are always referring to the implicit ancestor of every Object.
Upvotes: 3