python状态模式-小试牛刀
程序员文章站
2024-02-23 09:04:10
...
Python状态模式
状态模式
什么是状态模式,所谓状态模式是指对象在不同的状态下有不同的行为,这种不同的行为就好像是不同的类一样.
举例说明
在一个公司中,每个人都有自己的岗位和职责,假如我们实例化了两个人小白和小黄,都是公司的员工,结果天掉馅饼,小白被公司晋升为了经理,那小白的工作职能就改变了.这里就可以用状态模式来实现,当小白的身份状态变化时,其对应的行为方法也将改变!
Code(Python)
#encoding=utf-8
"""
状态模式小例程
"""
# 行为类,记录工作者所有存在的行为
class WorkerState(object):
def work(self):
pass
def resign(self):
pass
def makeplan(self, plan):
pass
class Staff(object):
def work(self):
print("staff work")
def resign(self):
print("I am resigning")
def makeplan(self, plan):
print("sorry, you don't have power to make plan")
class CEO(object):
def work(self):
print("ceo work")
def resign(self):
print("ceo resigning")
def makeplan(self, plan):
print("ceo are making "+plan)
class Worker(object):
def __init__(self, name):
self.name = name
self.setState(Staff())
def getState(self):
return self.worker_state
def setState(self, worker_state):
self.worker_state = worker_state
def work(self):
self.worker_state.work()
def resign(self):
self.worker_state.resign()
def makeplan(self, plan):
self.worker_state.makeplan(plan)
class Company(object):
def __init__(self, name):
self.name = name
self.persons = {}
def addPerson(self, person):
self.persons[person.name] = person
def delPerson(self, person):
del self.persons[person.name]
person.resign()
def listPerson(self):
for key in self.persons.keys():
print(self.persons[key].name)
def setCEO(self, person):
person.setState(CEO())
self.ceo = person
sanguo = Company("SAN GUO")
liubei = Worker("Liu Bei")
guanyu = Worker("Guan YU")
zhangfei = Worker("Zhang Fei")
zhaoyun = Worker("Zhao Yun")
zhugeliang = Worker("Zhuge Liang")
machao = Worker("Ma Chao")
pangtong = Worker("Pang Tong")
huangzhong = Worker("Huang Zhong")
sanguo.addPerson(liubei)
sanguo.addPerson(guanyu)
sanguo.addPerson(zhangfei)
sanguo.addPerson(zhaoyun)
sanguo.addPerson(zhugeliang)
sanguo.addPerson(machao)
sanguo.addPerson(pangtong)
sanguo.addPerson(huangzhong)
sanguo.setCEO(liubei)
sanguo.listPerson()
liubei.makeplan("兴复汉室")
for person in sanguo.persons.values():
person.work()
输出为:
Liu Bei
Ma Chao
Zhang Fei
Huang Zhong
Guan YU
Pang Tong
Zhao Yun
Zhuge Liang
ceo are making 兴复汉室
ceo work
staff work
staff work
staff work
staff work
staff work
staff work
staff work