An object in a program frequently has an internal "state", and the behavior of the object needs to change when its state changes. As someone who tends to think of objects as "data structures on steroids", it came as quite a shock when Netscape's Steve Abell pointed out that an object need not contain any values at all -- it can exist merely to provide behaviors, in the form of methods. This recipe demonstrates a networkcard that depends on its internal state connected/disconnected - to send/receive data.
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 61 62 63 64 65 66 67 68 69 | #!/usr/bin/env python
#
# Author: Bschorer Elmar
# State-Pattern Demo
class NetworkCardState:
"""Abstract State Object"""
def send(self):
raise "NetworkCardState.send - not overwritten"
def receive(self):
raise "NetworkCardState.receive - not overwritten"
class Online(NetworkCardState):
"""Online state for NetworkCard"""
def send(self):
print "sending Data"
def receive(self):
print "receiving Data"
class Offline(NetworkCardState):
"""Offline state for NetworkCard"""
def send(self):
print "cannot send...Offline"
def receive(self):
print "cannot receive...Offline"
class NetworkCard:
def __init__(self):
self.online = Online()
self.offline = Offline()
##default state is Offline
self.currentState = self.offline
def startConnection(self):
self.currentState = self.online
def stopConnection(self):
self.currentState = self.offline
def send(self):
self.currentState.send()
def receive(self):
self.currentState.receive()
def main():
myNetworkCard = NetworkCard()
print "without connection:"
myNetworkCard.send()
myNetworkCard.receive()
print "starting connection"
myNetworkCard.startConnection()
myNetworkCard.send()
myNetworkCard.receive()
if __name__ == '__main__':
main()
|
The example should output:
without connection: cannot send...Offline cannot receive...Offline starting connection sending Data receiving Data