Skip to content

Instantly share code, notes, and snippets.

@alvin2ye
Created November 11, 2009 02:46
Show Gist options
  • Select an option

  • Save alvin2ye/231510 to your computer and use it in GitHub Desktop.

Select an option

Save alvin2ye/231510 to your computer and use it in GitHub Desktop.
# state.rb 状态模式
class Connection
attr_accessor :state
def initialize
@state = TCPClose.new
end
def reset
@state = TCPClose.new
end
def disconnect
state.disconnect(self)
end
def connect
state.connect(self)
end
end
class TCPOpen
def disconnect(tcp)
puts "正在断开"
tcp.state = TCPClose.new
end
def connect(tcp)
puts "已经连着了, 不用再连"
end
end
class TCPClose
def disconnect(tcp)
puts "根本就没连上"
end
def connect(tcp)
puts "正在连接"
tcp.state = TCPOpen.new
end
end
if __FILE__ == $0
c = Connection.new
c.disconnect
c.connect
c.connect
c.disconnect
c.connect
c.reset
c.disconnect
end
=begin
根本就没连上
正在连接
已经连着了, 不用再连
正在断开
正在连接
根本就没连上
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment