python_类的设计模式

来源:互联网 发布:java 证书导出私钥 编辑:程序博客网 时间:2024/05/19 13:16
策略模式class Moveable:    def move(self):        print("move...")class Moveonfeet:    def move(self):        print("move on feet...")class Moveonwheel:    def move(self):        print("move on wheel...")class MoveObj:    def set_move(self,moveable):        self.moveable = moveable()    def move(self):        self.moveable.move()class Test:    def move(self):        print("I'm Fly.")if __name__ =='__main__':    m=MoveObj()    m.set_move(Moveable)    m.move()    m.set_move(Moveonfeet)    m.move()    m.set_move(Moveonwheel)    m.move()    m.set_move(Test)    m.move()


def Movea():    print("move a...")def Moveb():    print("move b...")class MoveObj:    def set_move(self,moveable):        self.moveable = moveable  #()    def move(self):        self.moveable()  #()if __name__ =='__main__':    m=MoveObj()    m.set_move(Movea)    m.move()    m.set_move(Moveb)    m.move()

#装饰模式class Tree:    def start(self):        print("tree a ...")    def mid(self):        print("tree b...")class Decorater:    def __init__(self,T):        self.t=T()    def add_start(self):        print("start first add...")        self.t.start()    def add_mid(self):        print("start second add...")        self.t.start()if __name__ == '__main__':    tree=Tree()    tree.start()    tree.mid()    dec=Decorater(Tree)    dec.add_start()    dec.add_mid()

def Decorater(a_class):    class NewClass:        def __init__(self,age,color):            self.old = a_class(age)            self.color = color        def display(self):            print(self.color)            print(self.old.age) #!!!    return NewClass@Decoraterclass Dog:    def __init__(self,age):        self.age = age    def display(self):        print(self.age)if __name__ == '__main__':    dog=Dog(12,'red')    print(dog.display())


1 0
原创粉丝点击