Last active
December 18, 2015 21:29
-
-
Save jyfeather/5847444 to your computer and use it in GitHub Desktop.
使用MVC框架的秒表程序 -- 来自《松本行弘的程序世界》
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# MVC(Model - View - Control)框架实例之秒表设计 | |
require 'observer' # 使用观察者模式 | |
# 模型(Model),时间计算 | |
class WatchModel | |
include Observable # 继承Observable接口,使WatchModel成为Observer模式中的观察对象 | |
def initialize | |
@running = false | |
@time = 0 | |
@last = 0.0 | |
Thread.start do # 计时器线程 | |
loop do | |
sleep 0.01 | |
if @running | |
now = Time.now.to_f | |
@time += now - @last | |
@last = now | |
changed | |
notify_observers(@time) | |
end | |
end | |
end | |
end | |
def start_stop # 控制秒表的启动和退出 | |
@last = Time.now.to_f | |
@running = !@running | |
end | |
def time | |
@time | |
end | |
end | |
# 视图(View),时间表示 | |
class WatchView | |
def initialize(model) | |
model.add_observer(self) # 使用 add_observer 使自己成为模型的观察者 | |
end | |
def update(time) # 在模型发生变更的时候调用 update 方法 | |
printf "\e[8D%02d:%02d", time.to_i, (time - time.to_i) * 100 | |
STDOUT.flush | |
end | |
end | |
# 控制(Control),用户操作,以及联系模型和视图 | |
class WatchController | |
def initialize | |
@model = WatchModel.new | |
@view = WatchView.new(@model) | |
system "stty cbreak -echo" # 设定终端响应键盘输入(cbreak模式) | |
begin | |
@view.update(@model.time) | |
loop do | |
break if STDIN.getc == ?q | |
@model.start_stop | |
end | |
ensure | |
system "stty cooked echo" # 结束后回到初始状态 | |
end | |
end | |
end | |
# 启动秒表 | |
WatchController.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment