本文主要是介绍Python 观察者模式 (刺客护卫攻防战),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
想了个挺二的例子。剑客是刺客,是被锁定的目标。忍者和火枪手是观察者,观察刺客的移动和负责攻击刺客。
lineseq = '==' * 20class Assassin( object ):def __init__( self, name, position ):self._name = nameself._position = position[:]self._list_of_observer_guards = []def be_locked_target( self, guard ):if guard not in self._list_of_observer_guards:self._list_of_observer_guards.append( guard )def be_released_target( self, guard ):try:self._list_of_observer_guards.remove( guard )except:passdef notify_observer_guards( self, info ):for guard in self._list_of_observer_guards:guard.notify( info )def move( self, dx, dy ):self._position[0] += dxself._position[1] += dyinfo = self._name + str( self._position )self.notify_observer_guards( info )def attack( self ):passclass Swordsman( Assassin ):def __init__( self, name, position, weapon ):super( Swordsman, self ).__init__( name, position )self._weapon = weapondef attack( self ):print lineseqprint 'Swordsman [%s]: My weapon [%s] is powerful and i prepare to attack'\%( self._name, self._weapon )info = self._name + ' is prepare to attack'self.notify_observer_guards( info )print lineseqclass Guard( object ):def __init__( self, name, position ):self._name = nameself._position = position[:]def notify( self, info ):passclass Ninja( Guard ):def __init__( self, name, position, weapon ):super( Ninja, self ).__init__( name, position )self._weapon = weapondef notify( self, info ):print lineseqprint 'Ninja [%s]: I have revice the information that [%s]'\%( self._name, info )print ' ' * 4 + 'My weapon is [%s]'%( self._weapon )print lineseqclass Hackbuteer( Guard ):def __init__( self, name, position, weapon ):super( Hackbuteer, self ).__init__( name, position )self._weapon = weapondef notify( self, info ):print lineseqprint 'Hackbuteer [%s]: I have revice the information that [%s]'\%( self._name, info )print ' ' * 4 + 'My weapon is [%s]'%( self._weapon )print lineseqif __name__ == '__main__':sword_scheme = Swordsman( 'Scheme', [ 100, 100 ], 'sword' )ninja_delusion = Ninja( 'Delusion', [50, 50], 'arrow' )hackbuteer_lambda = Hackbuteer( 'Lambda', [11, 11], 'firelock' )sword_scheme.be_locked_target( ninja_delusion )sword_scheme.be_locked_target( hackbuteer_lambda )sword_scheme.move( 1, 1 )sword_scheme.attack()print 'After be_released_target ninja_delusion'sword_scheme.be_released_target( ninja_delusion )sword_scheme.move( -5, 1 )sword_scheme.attack()
这篇关于Python 观察者模式 (刺客护卫攻防战)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!