策略模式,主要是针对不同的情况采用不同的处理方式。如商场的打折季,不同种类的商品的打折幅度不一,所以针对不同的商品我们就要采用不同的计算方式即策略来进行处理。
一、示例展示:
以下例子主要通过对手机和笔记本添加不同的策略来实现策略模式的应用!
1. 创建抽象策略角色:DailyProductStrategy
abstract class DailyProductStrategy
{
public abstract void AlgorithmInterface();
}
2. 创建具体策略角色:Handphone
class Handphone : DailyProductStrategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("Strategy A is using for handphone!");
}
}
3. 创建具体策略角色:Laptop
class Laptop : DailyProductStrategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("Strategy B is using for laptop!");
}
}
4. 创建环境角色:Context
class Context
{
DailyProductStrategy strategy; public Context(DailyProductStrategy strategy)
{
this.strategy = strategy;
} public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}
5. 创建客户端调用:
class Program
{
static void Main(string[] args)
{
Context c = new Context(new Handphone());
c.ContextInterface(); Context d = new Context(new Laptop());
d.ContextInterface(); Console.ReadLine();
}
}
二、策略模式设计理念:
策略模式主要包括三个角色:抽象策略角色,具体策略角色及环境角色。通过对策略中的不确定部分进行抽象,然后在具体策略角色中通过继承来实现不同的策略的实现细节。在环境角色中定义抽象策略对象,通过环境角色的构造方法,实现了对该抽象策略对象的初始化,也为策略模式的实现提供了最根本的灵活性!
三、角色及关系: