txlCandy 2020-04-20
程序员,我为你祝福
愿你有一个灿烂的前程
愿你有情人终成眷属
愿你在尘世获得幸福
我只想成为架构师,走遍江湖!
它定义一系列算法,将每一个算法封装起来,并让它们之间可以相互替换。此模式让算法的变化,不会影响到使用算法的客户,也称为政策模式(Policy)。
属于行为型模式。
主要成员:
Strategy.py
from abc import ABC, abstractmethod class Strategy(ABC): """抽象类""" def __init__(self): """构造函数""" @abstractmethod def algorithmInterface(self): """抽象方法"""
ConcreteStrategy.py
from Strategy import Strategy class ConcreteStrategyA(Strategy): def __init__(self): super().__init__() def algorithmInterface(self): print("算法A实现") class ConcreteStrategyB(Strategy): def __init__(self): super().__init__() def algorithmInterface(self): print("算法B实现")
Context.py
from Strategy import Strategy class Context(): def __init__(self): """构造函数""" def setStrategy(self, strategy): """设置算法""" self._strategy = strategy def contextInterface(self): """执行算法""" self._strategy.algorithmInterface()
Client.py
from Context import Context from ConcreteStrategy import ConcreteStrategyA, ConcreteStrategyB context = Context() context.setStrategy(ConcreteStrategyA()) context.contextInterface() context.setStrategy(ConcreteStrategyB()) context.contextInterface()
执行结果:
Strategy.cs
using System; namespace Strategy { public abstract class Strategy { public abstract void AlgorithmInterface(); } }
ConcreteStrategyA.cs
using System; namespace Strategy { public class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法A实现"); } } }
ConcreteStrategyB.cs
using System; namespace Strategy { public class ConcreteStrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法B实现"); } } }
Context.cs
using System; namespace Strategy { public class Context { private Strategy _strategy; public Context() { } public void SetStrategy(Strategy strategy) { _strategy = strategy; } public void ContextInterface() { _strategy.AlgorithmInterface(); } } }
Client.cs
using System; namespace Strategy { public class Client { public static void Main(string[] args) { var context = new Context(); context.SetStrategy(new ConcreteStrategyA()); context.ContextInterface(); context.SetStrategy(new ConcreteStrategyB()); context.ContextInterface(); Console.Read(); } } }
以下情况可以使用策略模式: