定義:封裝一組算法,讓算法之間可以相互替換
類圖:
C++實現:
#include<iostream>
using namespace std;
class IStrategy
{
public:
virtual void AlgorithmInterface() = 0;
};
class StrategyA :public IStrategy
{
public :
virtual void AlgorithmInterface()
{
cout << "A" << endl;
}
~StrategyA() {};
};
class StrategyB :public IStrategy
{
public:
virtual void AlgorithmInterface()
{
cout << "B" << endl;
}
~StrategyB() {};
};
class StrategyC :public IStrategy
{
public:
virtual void AlgorithmInterface()
{
cout << "C" << endl;
}
~StrategyC() {};
};
class Context
{
IStrategy* strategy;
public:
Context(IStrategy* strategy)
{
this->strategy = strategy;
}
void execute()
{
strategy->AlgorithmInterface();
}
};
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();
}
}
}