设计模式之开闭原则

面向对象程序应该 对扩展开放,对更改封闭。
如果更改代码,要重新编译,重新测试,重新部署,会附带很多其他操作。
python可以使用鸭子模式,进行多态调用。
如下, a和b可以独立变化,不影响以下代码的稳定:

self.x = a
self.x.duck()
self.x = b
self.x.duck()

正常模式:

# pay_money.py
#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~
def get_result(type, money):
"""商场促销"""
result = money
if money > 10000:
if type == "UserType.SILVER_VIP":
print("白银会员 优惠50元")
result = money - 50
elif type == "UserType.GOLD_VIP":
print("黄金会员 8折")
result = money * 0.8
elif type == "UserType.PLATINUM_VIP":
print("白金会员 优惠50元,再打7折")
result = money * 0.7 - 50
else:
print("普通会员 不打折")
result = money
return result

策略模式

class CashSuper(object):
"""收款抽象类"""
def pay_money(self,money):
pass
class SilverUser(CashSuper):
"""策略1:白银会员收费模式"""
def __init__(self, discount_money=50):
self.discount_money = discount_money
def pay_money(self,money):
return money - self.discount_money
class GoldUser(CashSuper):
"""策略2: 黄金会员收费模式"""
def __init__(self,discount=0.8):
self.discount = discount
def pay_money(self,money):
return money* self.discount
class PlatinumUser(CashSuper):
"""策略3: 白金会员收费模式"""
def __init__(self,discount_money=50,discount=0.7):
self.discount_money = discount_money
self.discount = discount
def pay_money(self,money):
if money >= self.discount_money:
return money* self.discount - self.discount_money
return money
class NormalUser(CashSuper):
"""策略4: 正常会员不打折"""
def pay_money(self,money):
return money
class Context(object):
"""具体实现的策略类"""
def __init__(self,cash_super):
"""初始化:将策略类传递进去作为属性"""
self.cash_super = cash_super
def get_result(self,money):
return self.cash_super.pay_money(money)
def main(money, user_type):
"""程序入口"""
if money < 1000:
return money
if user_type == "UserType.SILVER_VIP":
strategy = Context(SilverUser())
elif user_type == "UserType.GOLD_VIP":
strategy = Context(GoldUser())
elif user_type == "UserType.PLATINUM_VIP":
strategy = Context(PlatinumUser())
else:
strategy = Context(NormalUser())
return strategy.get_result(money)
posted @   道友请留步W  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示