1. 程式人生 > >設計模式學習總結(八)策略模式(Strategy)

設計模式學習總結(八)策略模式(Strategy)

isp 筆記本 override div ont 角色 write stat 通過

  策略模式,主要是針對不同的情況采用不同的處理方式。如商場的打折季,不同種類的商品的打折幅度不一,所以針對不同的商品我們就要采用不同的計算方式即策略來進行處理。

  一、示例展示:

  以下例子主要通過對手機和筆記本添加不同的策略來實現策略模式的應用!

  1. 創建抽象策略角色:DailyProductStrategy

技術分享
abstract class DailyProductStrategy
{
    public abstract void AlgorithmInterface();
}
View Code

  2. 創建具體策略角色:Handphone

技術分享
class Handphone : DailyProductStrategy
{
    
public override void AlgorithmInterface() { Console.WriteLine("Strategy A is using for handphone!"); } }
View Code

  3. 創建具體策略角色:Laptop

技術分享
class Laptop : DailyProductStrategy
{
    public override void AlgorithmInterface()
    {
        Console.WriteLine("Strategy B is using for laptop!
"); } }
View Code

  4. 創建環境角色:Context

技術分享
class Context
{
    DailyProductStrategy strategy;

    public Context(DailyProductStrategy strategy)
    {
        this.strategy = strategy;
    }

    public void ContextInterface()
    {
        strategy.AlgorithmInterface();
    }
}
View Code

  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();
    }
}
View Code

  二、策略模式設計理念:

  策略模式主要包括三個角色:抽象策略角色,具體策略角色及環境角色。通過對策略中的不確定部分進行抽象,然後在具體策略角色中通過繼承來實現不同的策略的實現細節。在環境角色中定義抽象策略對象,通過環境角色的構造方法,實現了對該抽象策略對象的初始化,也為策略模式的實現提供了最根本的靈活性!

  三、角色及關系:

  技術分享

設計模式學習總結(八)策略模式(Strategy)