Python设计模式:抽象工厂模式

设计模式二:抽象工厂模式

什么是抽象工厂模式

抽象工厂模式是工厂方法模式的一种泛化。当应用许多工厂方法时,将创建一系列对象的过程合并在一起会更合理,此时便引入了抽象工厂。

优点

1.让对象的创建更容易追踪 2.对象创建与使用解耦 3.提供优化内存占用和应用性能的潜力 4.通过改变激活的工厂方法动态地改变应用行为(例如应用切换风格)

实例代码

class MP3:
    def __init__(self):
        self.machine = MP3
    
    def __str__(self):
        return self.machine

    def play(self,play_file):
        print(Use {} play the {} : {}.format(self,play_file,play_file.getdata()))

class music:
    def __str__(self):
        return lalalalala.mp3
    def getdata(self):
        return lalalalala

class Listen_Factory:
    def __init__(self):
        print(self)

    def __str__(self):
        return ------Listen to the music ------
    
    def make_machine(self):
        return MP3()
    def play_file(self):
        return music()

class MP4:
    def __init__(self):
        self.machine = MP4
    
    def __str__(self):
        return self.machine

    def play(self,play_file):
        print(Use {} play the {} : {}.format(self,play_file,play_file.getdata()))

class movie:
    def __str__(self):
        return dididididi.mp4
    def getdata(self):
        return dididididi

class Watch_Factory:
    def __init__(self):
        print(self)

    def __str__(self):
        return ------Watch a movie ------
    
    def make_machine(self):
        return MP4()
    def play_file(self):
        return movie()

class Relax_Factory:
    def __init__(self,choose):
        self.machine = choose.make_machine()
        self.play_file = choose.play_file()
    
    def play(self):
        self.machine.play(self.play_file)

def main():
    print(Which one do you like?)
    print(1. Listen to music)
    print(2. Watch a movie)
    opt = input(Select the number
)
    opt = int(opt)
    choose = Listen_Factory if opt ==1 else Watch_Factory
    relax = Relax_Factory(choose())
    relax.play()

if __name__ == "__main__":
    main()
经验分享 程序员 微信小程序 职场和发展