设计模式:创建型模式python常用

  • 常见创建型设计模式
    • 工厂模式(Factory):解决对象创建问题
    • 构造模式(Builder):控制复杂对象的创建
    • 原型模式(Prototype):通过原型的克隆创建新的实例
    • 单例模式(Borg/Singleton):一个类只能创建同一个对象
    • 对象池模式(Pool):预先分配同一类型的一组实例
    • 惰性计算模式(Lazy Evaluation):延迟计算(python的property访问属性的时候才计算操作)
  • 工厂模式Factory
    • 解决对象创建问题
    • 解耦对象的创建和使用
    • 包括工厂方法和抽象工厂
    • class DogToy:
          def speak(self):
              print("wang wang")
      
      
      class CatToy:
          def speak(self):
              print("miao miao")
      
      
      def toy_factory(toy_type):
          if toy_type == 'dog':
              return DogToy()
          elif toy_type == 'cat':
              return CatToy()
  • 构造模式Builder
    • 用来控制复杂对象的构造
    • 创建和表示分离。比如你要买电脑,工厂模式直接给你需要的电脑。但是构造模式允许你自己定义电脑配置,组装完成后给你
    • # 一个构造模式例子
      
      class Computer:
          def __init__(self, serial_number):
              self.serial = serial_number
              self.memory = None
              self.hdd = None
              self.gpu = None
      
          def __str__(self):
              info = (
                  f'Memory {self.memory}GB',
                  f'Hard Disk:{self.hdd}GB',
                  f'Graphics Card:{self.gpu}GB'
              )
              return '\n'.join(info)
      
      
      class ComputerBuilder:
          def __init__(self):
              self.computer = Computer("AG23385193")
      
          def configure_memory(self, amount):
              self.computer.memory = amount
      
          def configure_hdd(self, amount):
              self.computer.hdd = amount
      
          def configure_gpu(self, gpu_model):
              self.computer.gpu = gpu_model
      
      
      class HardwareEngineer:
          def __init__(self):
              self.builder = None
      
          def construct_computer(self, memory, hdd, gpu):
              self.builder = ComputerBuilder()
              [step
               for step in
               (self.builder.configure_memory(memory),
                self.builder.configure_hdd(hdd),
                self.builder.configure_gpu(gpu))]
      
          @property
          def computer(self):
              return self.builder.computer
      
      
      # 使用builder可以创建多个builder类实现不同的组装方式
      engineer = HardwareEngineer()
      engineer.construct_computer(hdd=500,memory=8,gpu='GeForce GTX 650 Ti')
      computer = engineer.computer
      print(computer)
      
  • 原型模式Prototype
    • 通过克隆原型来创建新的实例
    • 可以使用相同的原型,通过修改部分属性来创建新的实例
    • 用途:对于一些创建实例开销比较高的地方可以用原型模式
  • 单例模式
    • 实现方式有多种
    • 一个类创建出来的对象都是同一个
    • python的模块就是单例,只会导入一次
    • 使用共享同一个实例的方式来创建单例模式
    • # 单例模式
      
      class Singleton:
          def __new__(cls, *args, **kwargs):
              if not hasattr(cls, '_instance'):
                  _instance = super().__new__(cls, *args, **kwargs)
                  cls._instance = _instance
              return cls._instance
      
      
      class MyClass(Singleton):
          pass
      
      
      c1 = MyClass()
      c2 = MyClass()
      assert c1 is c2 #单例的,c1和c2是同一个实例
      

      

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值