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
标签:MakeTrades,Python,Pattern,self,strategy,discount,Strategy,price,def From: https://www.cnblogs.com/geovindu/p/16826508.html