Python設計模式之策略模式實例詳解

這篇文章主要介紹了Python設計模式之策略模式,結合實例形式分析了策略模式的概念、原理並結合實例形式分析了Python定義與使用策略模式相關操作技巧,需要的朋友可以參考下

本文實例講述了Python設計模式之策略模式。分享給大家供大家參考,具體如下:

策略模式(Strategy Pattern):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶.

下面是一個商場活動的實現

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
'''
大話設計模式
設計模式——策略模式
策略模式(strategy):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶
'''
#現金收費抽象類
class CashSuper(object):
  def accept_cash(self,money):
    pass
#正常收費子類
class CashNormal(CashSuper):
  def accept_cash(self,money):
    return money
#打折收費子類
class CashRebate(CashSuper):
  def __init__(self,discount=1):
    self.discount = discount
  def accept_cash(self,money):
    return money * self.discount
#返利收費子類
class CashReturn(CashSuper):
  def __init__(self,money_condition=0,money_return=0):
    self.money_condition = money_condition
    self.money_return = money_return
  def accept_cash(self,money):
    if money>=self.money_condition:
      return money - (money / self.money_condition) * self.money_return
    return money
#具體策略類
class Context(object):
  def __init__(self,csuper):
    self.csuper = csuper
  def GetResult(self,money):
    return self.csuper.accept_cash(money)
if __name__ == '__main__':
  money = input("原價: ")
  strategy = {}
  strategy[1] = Context(CashNormal())
  strategy[2] = Context(CashRebate(0.8))
  strategy[3] = Context(CashReturn(100,10))
  mode = input("選擇折扣方式: 1) 原價 2) 8折 3) 滿100減10: ")
  if mode in strategy:
    csuper = strategy[mode]
  else:
    print "不存在的折扣方式"
    csuper = strategy[1]
  print "需要支付: ",csuper.GetResult(money)

運行結果:

原價: 500
選擇折扣方式: 1) 原價 2) 8折 3) 滿100減10: 2
需要支付:  400.0

這幾個類的設計如下圖:

使用一個策略類CashSuper定義需要的算法的公共接口,定義三個具體策略類:CashNormal,CashRebate,CashReturn,繼承於CashSuper,定義一個上下文管理類,接收一個策略,並根據該策略得出結論,當需要更改策略時,只需要在實例的時候傳入不同的策略就可以,免去了修改類的麻煩

更多關於Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧彙總》及《Python入門與進階經典教程

希望本文所述對大家Python程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章