策略模式,同一问题有多种不同的解法,即不同策略,一个物体可以动态地对策略进行更换。
class Stragety(object):
def __init__(self, name):
self.name = name
def do(self):
print(self.name)
class Question(object):
def __init__(self, question):
self.question = question
self.stragety = None
def set_stragety(self, stragety):
self.stragety = stragety
def solve(self):
self.stragety.do()
def main():
question = Question('need to solve problem')
stragety_a = Stragety('a')
question.set_stragety(stragety_a)
question.solve()
stragety_b = Stragety('b')
question.set_stragety(stragety_b)
question.solve()
if __name__ == '__main__':
main()
网友评论