Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

block the creation of multiple object of a class

How do I limit the object of any class to one. My class looks like :

class Speaker
  include Mongoid::Document
  field :name, :type => String
end

I just want to let a single instance of speaker . One way would be to add a validation which would check the number of objects already present of the Speaker class. Is there a ruby way of doing thing ?

like image 308
Prabesh Shrestha Avatar asked Aug 19 '11 11:08

Prabesh Shrestha


People also ask

Can we create multiple objects of same class?

A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object.

How do you prevent an object from being created in Java?

You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method Boolean. valueOf(String) is almost always preferable to the constructor Boolean(String).


1 Answers

How about using the Singleton module?

like image 62
Frank Schmitt Avatar answered Nov 19 '22 13:11

Frank Schmitt