学习版本3.5.2
#学习版本3.5.2
#访问者模式定义:封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据
#结构的前提下定义作用于这些元素的新操作
#举例子:系统访问玩家的等级
class Player(object):
def __init__(self, level):
self.level = level
def accept(self, visitor):
visitor.visit(self)
def showLevel(self):
print("level: ",self.level)
class PlayerList(object):
def __init__(self):
self.playerlist = []
for i in range(1,21):
self.playerlist.append(Player(i))
def getList(self):
return self.playerlist
class visitor(object):
pass
class GameSystem(visitor):
def visit(self, player):
player.showLevel()
if __name__ == "__main__":
playerlist = PlayerList()
for p in playerlist.getList():
p.accept(GameSystem())
运行结果
level: 1
level: 2
level: 3
level: 4
level: 5
level: 6
level: 7
level: 8
level: 9
level: 10
level: 11
level: 12
level: 13
level: 14
level: 15
level: 16
level: 17
level: 18
level: 19
level: 20