Skip to content

Commit 8e8f7aa

Browse files
committed
singleton pattern
1 parent a940506 commit 8e8f7aa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

singleton.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Define an unique instance of an object
2+
class HeroFactory
3+
@@instance = nil
4+
5+
def self.instance
6+
@@instance = HeroFactory.send(:new) unless @@instance
7+
@@instance
8+
end
9+
10+
def create_warrior
11+
Warrior.new
12+
end
13+
14+
def create_mage
15+
Mage.new
16+
end
17+
18+
private_class_method :new
19+
end
20+
21+
# Usage
22+
factory = HeroFactory.instance
23+
another_factory = HeroFactory.instance
24+
puts factory == another_factory
25+
# => true
26+
HeroFactory.new
27+
# => Raise Exception

0 commit comments

Comments
 (0)