首页 > 代码库 > Python 观察者模式 (刺客护卫攻防战)

Python 观察者模式 (刺客护卫攻防战)

想了个挺二的例子。剑客是刺客,是被锁定的目标。忍者和火枪手是观察者,观察刺客的移动和攻击。



lineseq = ‘==‘ * 20


class Assassin( object ):
    def __init__( self, name, position ):
        self._name = name
        self._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:
            pass

    def notify_observer_guards( self, info ):
        for guard in self._list_of_observer_guards:
            guard.notify( info )

    def move( self, dx, dy ):
        self._position[0] += dx
        self._position[1] += dy
        info = self._name + str( self._position )
        self.notify_observer_guards( info )

    def attack( self ):
        pass


class Swordsman( Assassin ):
    def __init__( self, name, position, weapon ):
        super( Swordsman, self ).__init__( name, position )
        self._weapon = weapon

    def attack( self ):
        print lineseq
        print ‘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 lineseq


class Guard( object ):
    def __init__( self, name, position ):
        self._name = name
        self._position = position[:]

    def notify( self, info ):
        pass

class Ninja( Guard ):
    def __init__( self, name, position, weapon ):
        super( Ninja, self ).__init__( name, position )
        self._weapon = weapon

    def notify( self, info ):
        print lineseq
        print ‘Ninja [%s]: I have revice the information that [%s]‘              %( self._name, info )
        print ‘ ‘ * 4 + ‘My weapon is [%s]‘%( self._weapon )
        print lineseq
    
class Hackbuteer( Guard ):
    def __init__( self, name, position, weapon ):
        super( Hackbuteer, self ).__init__( name, position )
        self._weapon = weapon

    def notify( self, info ):
        print lineseq
        print ‘Hackbuteer [%s]: I have revice the information that [%s]‘              %( self._name, info )
        print ‘ ‘ * 4 + ‘My weapon is [%s]‘%( self._weapon )
        print lineseq

if __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()