-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingle-Active-Instance_Singleton.rb
More file actions
60 lines (55 loc) · 998 Bytes
/
Single-Active-Instance_Singleton.rb
File metadata and controls
60 lines (55 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'singleton'
require 'thread'
class NullWorker
include Singleton
end
module Worker
@@active = NullWorker.instance
@@mutex = Mutex.new
def initialize(name)
@name = name
end
def activate
@@mutex.synchronize {
@@active = self
}
end
def to_s
"[Worker #{@name}]"
end
def Worker.activeWork(job)
@@mutex.synchronize {
@@active.work(job)
}
end
end
class NullWorker
include Worker
def initialize
super("The NullWorker")
end
def work(job)
puts "(#{job} is ignored by NullWorker)"
end
end
class PrintWorker
include Worker
def initialize(name)
super(name)
end
def work(job)
puts "#{self} does \"#{job}\"."
end
end
class Main
def Main.main
worker1 = PrintWorker.new("worker1")
worker2 = PrintWorker.new("worker2")
Worker.activeWork("Hello, worker!")
worker1.activate
Worker.activeWork("Hello, worker!")
worker2.activate
Worker.activeWork("Hello, worker!")
end
end
Main.main