The following is the singleton pattern in Ruby:
ruby 代码
- class Singleton
- private_class_method :new
- @@instance = nil
-
-
- def Singleton.instance
- if(@instance == nil)
- @instance = new
- end
- return @instance
- end
- end
and you can define two instances of this class by the instance method like this:
ruby 代码
- s = Singleton.instance
- s2 = Singleton.instance
then you can use this code to test whether the two instances are the same reference or not:
ruby 代码
If you run these codes,you can get 'true' in your console.
But there is a problem,this class can't work in mutl-thread
environment,is it right?
分享到:
相关推荐
在Ruby中,单例模式可以通过使用`singleton`模块或者定义私有构造函数并提供静态方法来实现。 ### 结构型模式 #### Adapter(适配器) 适配器模式将一个类的接口转换成客户希望的另一个接口。这种模式使原本由于...
Ruby中可以通过模块混入(Mix-in)或者模块方法(Module Methods)来实现策略模式,允许动态选择执行的算法。 6. **命令模式**(Command Pattern):命令模式将请求封装为一个对象,以便使用不同的请求、队列请求、...
- 单例模式(Singleton Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) - **动态语言Bean在Spring中的应用**:...
"DesignPattern"这个标题暗示我们将探讨在Ruby中应用的设计模式。 在Ruby中,有多种设计模式可以分为三类:创建型、结构型和行为型。这些模式都是从面向对象编程的原则和实践中提炼出来的,旨在提高代码的复用性和...
通过使用`singleton_class`和`instance_variable_set`方法,我们可以创建并控制单例对象。 2. **工厂模式**:在Rails中,ActiveRecord的`build`和`create`方法就是工厂方法的例子。它们负责创建和保存模型实例。...