python写了个命令模式

作者: Gevin | 来源:发表于2014-03-31 13:32 被阅读560次

    gist是个很有意思的github子产品,可谓之程序员的twitter,我前面文章中找的很多关于树莓派的资源,都来源于gist。在gist上分享自己的代码片段,是件有趣的事情,不知大家有哪些好玩的代码来分享一下?我在这里先抛砖引玉吧,分享一段我对命令模式的理解(python版),gist上链接请移步这里

    class Vehicle(object):
        """docstring for Vehicle"""
        def __init__(self):
            self.name = 'vehicle'
            
        def __call__(self):
            print "travelling by a Vehicle"
    
        def execute(self):
            self()
    
    
    class Bus(Vehicle):
        """docstring for Bus"""
        def __init__(self):
            super(Vehicle, self).__init__()
            self.name = 'bus'
    
        def __call__(self):
            print 'travelling by bus'
    
        def execute(self):
            self()
            
    class Bike(Vehicle):
        """docstring for Bike"""
        def __init__(self):
            super(Vehicle, self).__init__()
            self.name = 'bike'
    
        def __call__(self):
            print 'travelling by bike'
    
        def execute(self):
            self()
    
    class Car(Vehicle):
        """docstring for Car"""
        def __init__(self):
            super(Vehicle, self).__init__()
            self.name = 'car'
    
        def __call__(self):
            print 'travelling by car'
    
        def execute(self):
            self()
    
    class Rocket(Vehicle):
        """docstring for Rocket"""
        def __init__(self):
            super(Vehicle, self).__init__()
            self.name = 'rocket'
    
        def __call__(self):
            print 'travelling by rocket'
    
        def execute(self):
            self()
    
    
    class Traveller(object):
        """docstring for Traveller"""
        def __init__(self, name):
            self.name = name
    
        def set_vehicle(self, vehicle):
            self.vehicle = vehicle
            
        def travel(self):
            self.vehicle.execute()
    
    
    def main():
        # create a traveller
        tom = Traveller('tom')
    
        print 'stop 1:'
        # traveller's first vehicle
        vehicle = Bus()
        tom.set_vehicle(vehicle)
        tom.travel()
    
        print 'stop 2:'
        # traveller's second vehicle
        vehicle = Bike()
        tom.set_vehicle(vehicle)
        tom.travel()
    
        print 'stop 3:'
        # traveller's third vehicle
        vehicle = Car()
        tom.set_vehicle(vehicle)
        tom.travel()
    
        print 'stop 4:'
        # traveller's fourth vehicle
        vehicle = Rocket()
        tom.set_vehicle(vehicle)
        tom.travel()
    
    if __name__ == '__main__':
        main()
    
    ### OUTPUT ###
    # stop 1:
    # travelling by bus
    # stop 2:
    # travelling by bike
    # stop 3:
    # travelling by car
    # stop 4:
    # travelling by rocket
    

    相关文章

      网友评论

        本文标题:python写了个命令模式

        本文链接:https://www.haomeiwen.com/subject/asnktttx.html