- 论坛徽章:
- 0
|
最近在复习设计模式和操作系统原理发现state模式正好可以用来模拟操作系统中进程状态转化的表现,就用python实现了一下。因为是模拟所以只实现了最简单的三种进程状态:运行(RunningState),就绪(ReadyState),阻塞(BlockedState)。大概的思路是这样:首先定义一个抽象状态类ProcessState,这个类最主要的功能是提供状态转化的接口changeState(self,context)此函数的内容为context.changeState(self)也就是说要改变上下文context的状态,具体怎么改变,改变成什么样的状态就是靠ProcessState的具体类比如这里的RunningState,BlockedState,ReadyState来实现,例如:当进程在运行状态的时候(RunningState)发现需要等待某个事件,那么调用RunningState类的waitSth(self,context)函数,此函数就通过ProcessState.changeState(BlockedState().instance(),context)语句改变context的状态为BlockedState。之所以用BlockedState().instance()得到BlockedState的实例是因为所有的这些具体状态类都实现为单件模式(Singleton)。下面给出所有的源代码,欢迎大家交流。
class ProcessState:
def changeState(self,context):
context.changeState(self)
def getStateName(self):
return self.StateName
class RunningState(ProcessState):
__instance = None
def __init__(self):
__instance = self
self.StateName = 'RUNNING'
def instance(self):
if(RunningState.__instance == None):
RunningState.__instance = RunningState()
return RunningState.__instance
def waitSth(self,context):
print 'In Runing.waitSth() do some context switching'
ProcessState.changeState(BlockedState().instance(),context)
def goReady(self,context):
print 'In Running.goReady() do some context switching'
ProcessState.changeState(ReadyState().instance(),context)
class BlockedState(ProcessState):
__instance = None
def __init__(self):
__instance = self
self.StateName = 'BLOCKED'
def instance(self):
if(BlockedState.__instance == None):
BlockedState.__instance = BlockedState()
return BlockedState.__instance
def sthHappened(self,context):
print 'In BlockedState.sthHappened() do some context switching'
ProcessState.changeState(ReadyState().instance(),context)
class ReadyState(ProcessState):
__instance = None
def __init__(self):
__instance = None
self.StateName = 'READY'
def instance(self):
if(ReadyState.__instance == None):
ReadyState.__instance = ReadyState()
return ReadyState.__instance
def goRunning(self,context):
print 'In ReadyState.goRunning() do some context switching'
ProcessState.changeState(RunningState().instance(),context)
class ProcessContext:
def __init__(self):
self._state = ReadyState().instance()
def changeState(self,state):
self._state = state
def waitSth(self):
self._state.waitSth(self)
def goReady(self):
self._state.goReady(self)
def sthHappened(self):
self._state.sthHappened(self)
def goRunning(self):
self._state.goRunning(self)
def prtStateName(self):
print 'now the state of process is ',self._state.getStateName()
class Client:
def run(self):
ctx = ProcessContext()
ctx.prtStateName()
ctx.goRunning()
ctx.prtStateName()
ctx.waitSth()
ctx.prtStateName()
ctx.sthHappened()
ctx.prtStateName()
ctx.goRunning()
ctx.prtStateName()
ctx.goReady()
ctx.prtStateName()
if(__name__ == "__main__"):
client = Client()
client.run()
[ 本帖最后由 kimalise 于 2008-12-3 12:24 编辑 ] |
|