Python: Strategy Pattern
GeovinDuStrategy.py
# 策略模式 Strategy Pattern Types of trading strategies:
class RiskyTradingStrategy(object):
def MakeTrades(self):
print("进行高风险交易!")
class ModerateTradingStrategy(object):
def MakeTrades(self):
print("进行适度的交易.")
class ConservativeTradingStrategy(object):
def MakeTrades(self):
print("进行安全交易.")
# Not Supported below Python 3.4!
from enum import Enum
class TradeConditions(Enum):
BearMarket = 0,
BullMarket = 1,
RecoveringMarket = 2
# The trading firm which changes strategies based on market conditions:
class TradingFirm(object):
def __init__(self):
self.riskyStrategy = RiskyTradingStrategy()
self.moderateStrategy = ModerateTradingStrategy()
self.safeStrategy = ConservativeTradingStrategy()
self.currentStrategy = self.moderateStrategy
def MarketUpdte(self, tradeConditions):
# Select the best strategy for the market conditions:
if tradeConditions == TradeConditions.BearMarket:
self.currentStrategy = self.safeStrategy
elif tradeConditions == TradeConditions.BullMarket:
self.currentStrategy = self.riskyStrategy
elif tradeConditions == TradeConditions.RecoveringMarket:
self.currentStrategy = self.moderateStrategy
# Make trades with that strategy:
self.currentStrategy.MakeTrades()
class Item:
"""Constructor function with price and discount"""
def __init__(self, price, discount_strategy=None):
"""take price and discount strategy"""
self.price = price
self.discount_strategy = discount_strategy
"""A separate function for price after discount"""
def price_after_discount(self):
if self.discount_strategy:
discount = self.discount_strategy(self)
else:
discount = 0
return self.price - discount
def __repr__(self):
statement = "价格: {}, 折扣后的价格: {}"
return statement.format(self.price, self.price_after_discount())
"""function dedicated to On Sale Discount"""
def on_sale_discount(order):
return order.price * 0.25 + 20
"""function dedicated to 20 % discount"""
def twenty_percent_discount(order):
return order.price * 0.20
main.py 调用
# 策略模式 Strategy Pattern higeovindu=GeovinDuStrategy.TradingFirm() higeovindu.MarketUpdte(higeovindu.moderateStrategy.MakeTrades()) higeovindu.safeStrategy.MakeTrades() higeovindu.currentStrategy.MakeTrades() higeovindu.riskyStrategy.MakeTrades() print(GeovinDuStrategy.Item(20000)) """with discount strategy as 20 % discount""" print(GeovinDuStrategy.Item(20000, discount_strategy=GeovinDuStrategy.twenty_percent_discount)) """with discount strategy as On Sale Discount""" print(GeovinDuStrategy.Item(20000, discount_strategy=GeovinDuStrategy.on_sale_discount))
输出:
进行适度的交易. 进行适度的交易. 进行安全交易. 进行适度的交易. 进行高风险交易! 价格: 20000, 折扣后的价格: 20000 价格: 20000, 折扣后的价格: 16000.0 价格: 20000, 折扣后的价格: 14980.0




哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号