溫馨提示×

Ruby單例模式如何初始化

小樊
81
2024-11-01 21:05:05
欄目: 編程語言

在Ruby中,單例模式可以通過使用模塊或類來實現。這里有兩種方法來初始化單例模式:

方法1:使用模塊

module Singleton
  def self.included(base)
    base.class_eval do
      @instance = nil

      def self.instance
        @instance ||= new
      end

      def self.new(*args, &block)
        raise "Singleton class can't be instantiated"
      end
    end
  end
end

class MyClass
  include Singleton

  def initialize(name)
    @name = name
  end
end

my_instance1 = MyClass.instance
my_instance2 = MyClass.instance

puts my_instance1.object_id == my_instance2.object_id # 輸出 true,表示兩個實例是同一個對象

方法2:使用類變量

class SingletonClass
  @@instance = nil

  def self.instance
    @@instance ||= new
  end

  def self.new(*args, &block)
    raise "Singleton class can't be instantiated"
  end
end

class MyClass < SingletonClass
  def initialize(name)
    @name = name
  end
end

my_instance1 = MyClass.instance
my_instance2 = MyClass.instance

puts my_instance1.object_id == my_instance2.object_id # 輸出 true,表示兩個實例是同一個對象

這兩種方法都可以實現單例模式,確保一個類只有一個實例,并提供一個全局訪問點。

0