python 面向对象—设计模式

  • 1.__new__(cls) 默认调用object的new 方法
    • 使用该方法创建当前实例对象,一般不重写,就算重写
    • 也是调用父类的__new__方法,注意:一定要返回创建的对象
    • 如果没有返回,__init__方法将不会被Python解释器调用
    • cls是类对象
    • __init__有一个参数self,就是这个__new__返回的实例,__init__在__new__的基础上可以完成一些其它初始化的动作,__init__不需要返回值。
  • 2.设计模式 设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。
    • 1.工厂模式
      • 工厂模式:
        • 1.简单工厂模式: 根据参数,造对象    缺点:类型不能扩展
        • 2.工厂方法模式: 一个类别对应一个工厂, 好处:1.可以产生多种类型  2.如果有需要修改的类别,对其他的不会有影响
    • shoe  ---> 皮鞋 球鞋  布鞋  ---->工厂
    • # 鞋 父类
    • class Shoe:
      • def walk(self):
        • pass
    • class LeatherShoe(Shoe):
      • def walk(self):
        • print("穿着亮亮的皮鞋,自信满满上班去了....")
    • class SoccerShoe(Shoe):
      • def walk(self):
        • print("穿着白白球鞋,去踢球.....")
    • # 定义工厂
    • class ShoeFactory:
      • def make_shoe(self):
        • pass
    • class LeatherShoeFactory(ShoeFactory):
      • # 重写父类的make_shoe
      • def make_shoe(self):
        • return LeatherShoe()
    • class SoccerShoeFactory(ShoeFactory):
      • def make_shoe(self):
        • return SoccerShoe()
    • class Store:
      • def sell(self,shoe_type):
        • if shoe_type=="皮鞋":
          • self.factory=LeatherShoeFactory()
        • elif shoe_type=="球鞋":
          • self.factory=SoccerShoeFactory()
    • store=Store()
    • store.sell("皮鞋")
    • store.factory.make_shoe().walk()
    • 2.单例模式
      • 即一个类只有一个对象实例。(创建的对象id相同)
      • class Singleton:
        • # 类属性   私有
        • __instance=None
        • # 控制__init__的执行
        • __init__flag=False
        • # 重写__new__
        • def  __new__(cls,name):  # cls 就是Singleton对象
          • if cls.__instance==None:
            • cls.__instance=object.__new__(cls)
            • return  cls.__instance
          • else:
            • return cls.__instance
        • def __init__(self,name):
          • if not self.__init__flag:
            • self.name=name
          • print("-------init-----------",name)
          • # 记住改变标志
          • self.__init__flag=True
      • s1=Singleton("aa")
      • print(id(s1))
      • print(s1.name)
      • s2=Singleton("bb")
      • print(id(s2))
      • print(s2.name)
      • s3=Singleton("cc")
      • print(id(s3))
      • print(s3.name)
  • 3.代理模式
    • 代理模式一般涉及到的角色有:
    • 抽象角色:声明真实对象和代理对象的共同基类(接口);
    • 代理角色:代理对象角色内部含有对真实对象的引用,从而可以操作真实对象,同时代理对象提供与真实对象相同的基类(接口)以便在任何时刻都能代替真实对象。
    • 同时,代理对象可以在执行真实对象操作时,附加其他的操作,相当于对真实对象进行封装。
    • 真实角色:代理角色所代表的真实对象,是我们最终要引用的对象。
    • 步骤:  隐藏一部分类信息,使用的时候直接招代理   类似(中介)
      • 1. 三要素: 抽象角色  真实角色  代理角色
      • 2. 代理跟真实角色之间是如何关联:
        • 代理类中存在一个真实角色属性
      • 3.代理来说:更换真实角色
        • 在代理类中定义了set_xxx(self,真实对象)
      • 4.创建代理对象,代理对象调用方法.而调用方法的时候就去找真实角色
        • 优点: 隐藏信息
        • 缺点: 如果应用代理比较多的情况下,会降低了速度
    • 抽象角色: 基类 父类
    • 代理角色: 王婆
    • 真实角色: 潘金莲
    • class kindWoman:
    • # 抛媚眼
      • def make_eyes_with_man(self):
        • pass
    • # 代理
    • class WangPo(kindWoman):
      • def __init__(self):
        • self.woman=PanJinLian()
      • def set_woman(self,kind_woman):
        • self.woman=kind_woman
      • def make_eyes_with_man(self):
        • self.woman.make_eyes_with_man()
      • # 真实角色
      • class PanJinLian(kindWoman):
        • def make_eyes_with_man(self):
          • print("潘金莲抛媚眼.....")
      • class JiaShi(kindWoman):
        • def make_eyes_with_man(self):
          • print("贾氏抛媚眼.....")
      • class XimenQing:
        • def start(self):
          • # 测试王婆
          • wangpo=WangPo()
          • wangpo.make_eyes_with_man()
          • # 修改kindwoman
          • jia=JiaShi()
          • wangpo.set_woman(jia)
          • wangpo.make_eyes_with_man()
      • xmq=XimenQing()
      • xmq.start()
### Python 面向对象设计模式实例 #### 命令模式的应用实例 命令模式属于行为型设计模式之一,主要用于解耦请求发送者和接收者之间的关系。通过引入中间层即命令类,使得两者之间不再直接交互。 ```python from abc import ABC, abstractmethod # 定义命令接口 class Command(ABC): @abstractmethod def execute(self): pass # 接收者类 class Light: def on(self): print("Light is ON") def off(self): print("Light is OFF") # 具体命令实现 class LightOnCommand(Command): def __init__(self, light: Light): self._light = light def execute(self): self._light.on() class LightOffCommand(Command): def __init__(self, light: Light): self._light = light def execute(self): self._light.off() ``` 上述代码展示了如何利用命令模式分离操作发起方与实际执行逻辑[^4]。 为了使这个例子更加完整,下面展示了一个简单的遥控器模拟场景: ```python # 调用者/客户端角色 class RemoteControl: def set_command(self, command: Command): self.command = command def press_button(self): if isinstance(self.command, Command): self.command.execute() if __name__ == "__main__": # 创建接收者对象 living_room_light = Light() # 构建具体命令并关联至接收者 turn_on_living_room_light = LightOnCommand(living_room_light) turn_off_living_room_light = LightOffCommand(living_room_light) remote_control = RemoteControl() # 设置并触发开灯动作 remote_control.set_command(turn_on_living_room_light) remote_control.press_button() # 切换成关灯指令再触发 remote_control.set_command(turn_off_living_room_light) remote_control.press_button() ``` 此案例说明了命令模式的核心思想:将“做什么”同“怎么做”分离开来处理;同时也体现了面向对象编程中的多态特性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值