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\n')
    opt = int(opt)
    choose = Listen_Factory if opt ==1 else Watch_Factory
    relax = Relax_Factory(choose())
    relax.play()

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值