天翼云代理,天翼云代理商,北京代理商
天翼云2.5折专线:18510009100/18510009200(全国市话)

Python编程:设计模式之单例和简单工厂

2021-11-23 09:27:47
简介: Python编程:设计模式之单例和简单工厂

前言

设计模式:

一种解决问题的思想和方法


设计模式原则:

高内聚、低耦合


设计模式分类(三大类23种)

创建类设计模式

单例模式、简单工厂模式、工厂模式、抽象工厂模式、原型模式、建造者模式;


结构类设计模式

装饰器模式、适配器模式、门面模式、组合模式、享元模式、桥梁模式;


行为类设计模式

策略模式、责任链模式、命令模式、中介者模式、模板模式、迭代器模式、访问者模式、观察者模式、解释器模式、备忘录模式、状态模式。


单例模式

# 1、Python与设计模式--单例模式 # https://yq.aliyun.com/articles/70418  import threading import time  # 抽象单例 class Singleton(object):  def __new__(cls, *args, **kwargs):  if not hasattr(cls, "_instance"):  cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)  return cls._instance  # 总线 class Bus(Singleton):  lock = threading.RLock()  def sendData(self, data):  Bus.lock.acquire()  time.sleep(3)  print("sendData:", data)  Bus.lock.release()  # 线程对象 class VisitEntity(threading.Thread):  my_bus = ""  name = ""  def getName(self):  return name   def setName(self, name):  self.name = name   def run(self):  self.my_bus = Bus()  self.my_bus.sendData(self.name)  if __name__ == '__main__':  for i in range(3):  print("run %s"%(i))  my_entity = VisitEntity()  my_entity.setName("entity_" + str(i))  my_entity.start()  """ run 0 run 1 run 2 sendData: entity_0 sendData: entity_1 sendData: entity_2 """  # 关于super   http://python.jobbole.com/86787/

简单工厂模式

 # 设计模式之简单工厂模式 # http://mp.weixin.qq.com/s/3J0hq3I95iKnbT5YjniZVQ  """ 简单工厂模式: 专门定义一个 工厂类 来负责创建 产品类 的实例,被创建的产品通常都具有共同的父类。  三个角色: 简单工厂(SimpleProductFactory)角色 抽象产品(Product)角色 具体产品(Concrete Product)角色 """  # 抽象产品 class Fruit(object):  def produce(self):  print("Fruit is prodeced")  # 具体产品 class Apple(Fruit):  def produce(self):  print("Apple is produced")  class Banana(Fruit):  def produce(self):  print("Banana is produced")  # 简单工厂 class Factory(object):  def produceFruit(self, fruit_name):  if fruit_name == "apple":  return Apple()  elif fruit_name == "banana":  return Banana()  else:  return Fruit()   if __name__ == '__main__':  factory = Factory()   apple = factory.produceFruit("apple")  apple.produce()   banana = factory.produceFruit("banana")  banana.produce()   fruit = factory.produceFruit("fruit")  fruit.produce() """ Apple is produced Banana is produced Fruit is prodeced """
12年经验 · 提供上云保障

服务热线:132-6161-6125(手机) 400-150-1900(全国市话)

站内导航: 天翼云服务器价格| 天翼云购买流程| 天翼云代理| 北京天翼云代理商| 杭州天翼云代理| 深圳天翼云代理商| 钉钉代理商| 阿里云代理| 公司官网

我公司收款账号| 天翼云备案系统

CopyRight © 2019 天翼云代理商. All Rights Reserved 京ICP备2024071855号-7 管理-北京优胜智连科技有限公司