간단한 싱글톤 디자인패턴 구현
<Tutorial-01-Class-Singleton.rb>
class MySingleton
private_class_method :new # 객체 생성을 위한 유일한 method인 new 를 private 으로 정의
@@singleton = nil
def initialize(name, age)
@name = name
@age = age
end
def MySingleton.create(name, age) # 싱글톤 객체를 생성하기 위한 클래스 메서드를 정의
@@singleton = new(name, age) unless @@singleton
@@singleton
end
def getMySingleton
puts "My name is #{@name} and I am #{@age.to_s} years old"
end
end
singletonTest1 = MySingleton.create("John lennon", 32)
singletonTest2 = MySingleton.create("Metalica", 33)
singletonTest1.getMySingleton # 싱글톤 객체 생성, 유일한 객체
singletonTest2.getMySingleton # 객체 생성 시도, 이미 생성된 객체 반환
댓글 없음:
댓글 쓰기