-- flyaflya [2005-08-04 09:32:34]

1. state(代理)

1.1. 意图

允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

1.2. 代码

   1 class NetworkCardState:
   2     """Abstract State Object"""
   3     def send(self):
   4         raise "NetworkCardState.send - not overwritten"
   5 
   6     def receive(self):
   7         raise "NetworkCardState.receive - not overwritten"
   8 
   9 
  10 class Online(NetworkCardState):
  11     """Online state for NetworkCard"""
  12     def send(self):
  13         print "sending Data"
  14 
  15     def receive(self):
  16         print "receiving Data"
  17 
  18 
  19 class Offline(NetworkCardState):
  20     """Offline state for NetworkCard"""
  21     def send(self):
  22         print "cannot send...Offline"
  23 
  24     def receive(self):
  25         print "cannot receive...Offline"
  26 
  27 
  28 class NetworkCard:
  29     def __init__(self):
  30         self.online = Online()
  31         self.offline = Offline()
  32         ##default state is Offline
  33         self.currentState = self.offline
  34 
  35     def startConnection(self):
  36         self.currentState = self.online
  37 
  38     def stopConnection(self):
  39         self.currentState = self.offline
  40 
  41     def send(self):
  42         self.currentState.send()
  43 
  44     def receive(self):
  45         self.currentState.receive()
  46 
  47 
  48 def main():
  49     myNetworkCard = NetworkCard()
  50     print "without connection:"
  51     myNetworkCard.send()
  52     myNetworkCard.receive()
  53     print "starting connection"
  54     myNetworkCard.startConnection()
  55     myNetworkCard.send()
  56     myNetworkCard.receive()
  57 
  58 if __name__ == '__main__':
  59     main()

1.3. 特殊说明