`
reverocean
  • 浏览: 197433 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Singleton pattern in Ruby

    博客分类:
  • Ruby
阅读更多
The following is the singleton pattern in Ruby:
ruby 代码
 
  1. class Singleton  
  2.     private_class_method :new  
  3.     @@instance = nil  
  4.       
  5.       
  6.     def Singleton.instance  
  7.         if(@instance == nil)  
  8.             @instance = new  
  9.         end  
  10.         return @instance  
  11.     end  
  12. end  
and you can define two instances of this class by the instance method like this:
ruby 代码
  1. s = Singleton.instance  
  2. s2 = Singleton.instance  

then you can use this code to test whether the two instances are the same reference or not:
ruby 代码
  1. puts s.equal?(s2)  
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?
分享到:
评论

相关推荐

    gof patterns in ruby

    在Ruby中,单例模式可以通过使用`singleton`模块或者定义私有构造函数并提供静态方法来实现。 ### 结构型模式 #### Adapter(适配器) 适配器模式将一个类的接口转换成客户希望的另一个接口。这种模式使原本由于...

    design-patterns-ruby:Ruby设计模式

    Ruby中可以通过模块混入(Mix-in)或者模块方法(Module Methods)来实现策略模式,允许动态选择执行的算法。 6. **命令模式**(Command Pattern):命令模式将请求封装为一个对象,以便使用不同的请求、队列请求、...

    Groovy 介绍 官网资源

    - 单例模式(Singleton Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) - **动态语言Bean在Spring中的应用**:...

    DesignPattern

    "DesignPattern"这个标题暗示我们将探讨在Ruby中应用的设计模式。 在Ruby中,有多种设计模式可以分为三类:创建型、结构型和行为型。这些模式都是从面向对象编程的原则和实践中提炼出来的,旨在提高代码的复用性和...

    rails-design-pattern:Rails框架中的设计模式

    通过使用`singleton_class`和`instance_variable_set`方法,我们可以创建并控制单例对象。 2. **工厂模式**:在Rails中,ActiveRecord的`build`和`create`方法就是工厂方法的例子。它们负责创建和保存模型实例。...

Global site tag (gtag.js) - Google Analytics