定义:封装一组算法,让算法之间可以相互替换
类图:
C++实现:
#include<iostream>
using namespace std;
class IStrategy
{
public:
virtual void AlgorithmInterface() = 0;
virtual ~IStrategy() = default;
};
class StrategyA :public IStrategy
{
public:
virtual void AlgorithmInterface()
{
cout << "A" << endl;
}
virtual ~StrategyA() {};
};
class StrategyB :public IStrategy
{
public:
virtual void AlgorithmInterface()
{
cout << "B" << endl;
}
virtual ~StrategyB() {};
};
class StrategyC :public IStrategy
{
public:
virtual void AlgorithmInterface()
{
cout << "C" << endl;
}
virtual ~StrategyC() {};
};
class Context
{
IStrategy* strategy;
public:
Context(IStrategy* strategy)
{
this->strategy = strategy;
}
void execute()
{
strategy->AlgorithmInterface();
}
~Context() {}
};
int main()
{
IStrategy* strategy;
StrategyA strategyA;
StrategyB strategyB;
StrategyC strategyC;
strategy = &strategyA;
Context context1(strategy);
context1.execute();
strategy = &strategyB;
Context context2(strategy);
context2.execute();
strategy = &strategyC;
Context context3(strategy);
context3.execute();
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
interface IStrategy
{
void AlgorithmInterface();
}
class StrategyA :IStrategy
{
public void AlgorithmInterface()
{
Console.WriteLine("A");
}
}
class StrategyB : IStrategy
{
public void AlgorithmInterface()
{
Console.WriteLine("B");
}
}
class StrategyC : IStrategy
{
public void AlgorithmInterface()
{
Console.WriteLine("C");
}
}
class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void execute()
{
strategy.AlgorithmInterface();
}
}
class Program
{
static void Main(string[] args)
{
StrategyA strategyA = new StrategyA();
StrategyB strategyB = new StrategyB();
StrategyC strategyC = new StrategyC();
Context context = new Context(strategyA);
context.execute();
context = new Context(strategyB);
context.execute();
context = new Context(strategyC);
context.execute();
}
}
}