using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
StrategyMordern
{
/// <summary>
/// 抽象算法类
/// </summary>
abstract
class
Strategy
{
//算法方法
public
abstract
void
AlgorithmInterface();
}
class
ConcreteStrategyA : Strategy
{
//算法A实现方法
public
override
void
AlgorithmInterface()
{
Console.WriteLine(
"算法A实现"
);
}
}
class
ConcreteStrategyB : Strategy
{
//算法B实现方法
public
override
void
AlgorithmInterface()
{
Console.WriteLine(
"算法B实现"
);
}
}
class
ConcreteStrategyC : Strategy
{
//算法C实现方法
public
override
void
AlgorithmInterface()
{
Console.WriteLine(
"算法C实现"
);
}
}
/// <summary>
/// Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。
/// </summary>
class
Context
{
Strategy strategy;
public
Context(Strategy strategy)
{
this
.strategy = strategy;
}
//上下文接口
public
void
ContextInterface()
{
strategy.AlgorithmInterface();
}
}
}
//Main函数主界面
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
StrategyMordern
{
class
Program
{
static
void
Main(
string
[] args)
{
Context context;
context =
new
Context(
new
ConcreteStrategyA());
context.ContextInterface();
context =
new
Context(
new
ConcreteStrategyB());
context.ContextInterface();
context =
new
Context(
new
ConcreteStrategyC());
context.ContextInterface();
Console.Read();
}
}
}
代码都是书里看到的,自己手写的。大家共同学习。