65.9K
CodeProject 正在变化。 阅读更多。
Home

面向初学者的策略设计模式示例

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.31/5 (13投票s)

2010年10月26日

CPOL

3分钟阅读

viewsIcon

56080

downloadIcon

423

本示例展示了如何以及在何处实现策略设计模式。

引言

有时候,我们需要根据某些条件执行多个计算/算法。我们通常通过使用`switch`语句、三元运算符或`if else`语句来实现这些操作。虽然最初我们可以设法编写这些程序,但如果程序需求过于复杂,那么编写和维护这样的程序就会很困难。

此外,将所有逻辑都写在一个地方是不可取的,因为它会导致紧耦合。

背景

在许多情况下,我们需要编写计算逻辑/算法,我们通常通过使用`if else`/`switch`语句或三元运算符来完成。有时候编写这样的程序会变得很困难,并且在后续的维护中会增加很多成本。

救援者

策略设计模式。它属于行为型模式类别。

如何

  1. 将客户端和算法/计算逻辑解耦到单独的类中
  2. 有助于随时切换算法
  3. 轻松插入新算法

模式组成部分

策略模式包含以下组成部分

  1. 策略接口 - 所有具体策略通用的接口
  2. 具体策略/不同的算法类 - 实现策略接口的各种具体类,用于实现其自身特有的算法
  3. Context 类 - 将请求委托给从客户端接收到的指示的具体策略。它这样做是因为它保留了具体策略的引用。
  4. 客户端 - 在这种情况下,是 Windows 窗体

案例研究

让我们以 MSWord 应用程序为例。各种字体样式(例如粗体、斜体等)可以使用这种设计模式来实现。让我们看看下面是如何实现的。

策略接口的实现

IFontStyle接口如下所示

public interface IFontStyle
{
   public Font GetNewFontStyle(Control c);
}

具体策略的实现

有四个具体策略类,即 _Bold.cs_、_Italic.cs_、_Underline.cs_ 和 _StrikeThru.cs_。

由于在本例中,所有类都遵循相同的模式,因此为了简单起见,我只描述了 Bold 具体类。

它如下所示

public class Bold : IFontStyle
{
        #region IFontStyle Members

        public Font GetNewFontStyle(System.Windows.Forms.Control c)
        {
            return new Font(c.Font, FontStyle.Bold);
        }

        #endregion
}

代码是不言自明的。Bold 类实现了策略接口 IFontStyle,它将字体样式作为 粗体 返回。

Context 的实现

FontStyleContext 类如下

public class FontStyleContext
{
        //step 1: Create an object of Strategy Interface
        IFontStyle _IFontStyle;

        //step 2:Set the concrete call called by the client to the 
        //interface object defined in the step 1
        public FontStyleContext(IFontStyle IFontStyle)
        {
            this._IFontStyle = IFontStyle;
        }

        //step 3: A method that will return the font style
        public Font GetFontStyle(Control c)
        {
            return _IFontStyle.GetNewFontStyle(c);
        }
}

客户端的实现

客户端设计如下

1.JPG

Bold 按钮点击事件的代码如下

// Bold Click
private void btnBold_Click(object sender, EventArgs e)
{
  objFontStyleContext = new FontStyleContext(new Bold());
  richTextArea.Font =  objFontStyleContext.GetFontStyle(richTextArea);           
}

首先,我们创建了 FontStyleContext 类的实例,然后使用相应的 StrategyConcrete 类实例化它。接下来,通过调用 GetFontStyle 方法,我们能够为 richtextbox 设置适当的 Font 样式。

其他按钮将具有相同的实现,仅调用相应的具体类。

输出

2.jpg

Resource

结论

在实现将根据条件调用的程序逻辑时,策略模式非常重要。这只是一个简单的例子,用于演示模式思想。在实际应用中,我们将面临更复杂的情况,但基本概念将保持不变。

欢迎对该主题进行改进提出评论。

感谢阅读本文。

历史

  • 2010年10月26日:首次发布
© . All rights reserved.