策略模式

一、概念

策略模式(Strategy):它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)

 

 

图1 策略模式类图

 优点:

  1、 简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
  2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
      3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。

  缺点:
  1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。
      2、 在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。(这本身没有解除客户端需要选择判断的压力,而策略模式与简单工厂模式结合后,选择具体实现的职责也可以由Context来承担,这就最大化的减轻了客户端的压力。)

参考阅读: 
1. 2.

 二、我的理解

其实这个策略模式和简单工厂模式一样,仅仅是对面向对象继承中常用的Override技术的一种应用。简单工厂模式中有一个工厂类,负责根据输入参数的不同来生成不同的子类,并将生成的子类作为基类返回(这样可以让客户端在使用的时候很方便)。客户端只需要调用工厂类创建一个基类的实例,然后调用这个实例的函数来实现自己的功能。而策略模式中的Context类的功能基本上就是对工厂类的强化版本,它也负责根据输入参数来生成不同的类,只是它并不返回生成类,而是将生成类所实现的功能接口包装一次,提供给客户。这样对客户来说,他们只需要知道这一个Context类就可以完成他们想要的功能,而不必再知道其他的信息。

三、策略模式与简单工厂模式结合的代码实现

下面以一个简单的商场收银系统为例,演示一下策略模式与简单工厂模式结合的使用。我将这个系统用两个工程实现。一个工程实现商场计费的业务功能,另一个工程用于实现POS机上的界面,也就是客户端。

首先介绍第一个工程:

1. 实现计费功能的基类(这里用抽象类实现): 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategeDemo
{
    public abstract class BillingAlgorithm
    {
        public abstract double getBillingResult(double price, int quantity);
    }
}
 

2. 实现具体计费功能的子类:

     2.1 实现打折计费的子类:    

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategeDemo
{
    public class BillingStrategy_Rebate : BillingAlgorithm
    {
        double discounts;
        public BillingStrategy_Rebate(double discounts)
        {
            if (discounts < 0.0000001 || discounts >= 1)
            {
                this.discounts = 1;
            }
            else
            {
                this.discounts = discounts;
            }
        }
        public override double getBillingResult(double price, int quantity)
        {
            return price * quantity * discounts;
        }
    }
}
 

     2.2 实现返现计费功能的子类:     

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategeDemo
{
    public class BillingStrategy_CashReturn : BillingAlgorithm
    {
        int CashCondition;
        int CashReturn;
        public BillingStrategy_CashReturn(int CashCondition, int CashReturn)
        {
            if (CashCondition <= 0)
            {
                CashCondition = 1;
            }
            if (CashReturn <= 0)
            {
                CashReturn = 1;
            }
            this.CashCondition = CashCondition;
            this.CashReturn = CashReturn;
        }
        public override double getBillingResult(double price, int quantity)
        {
            double orignal = price * quantity;
            int n = (int)(orignal / CashCondition);
            return orignal - CashReturn * n;
        }
    }
}
 

3. Context类

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategeDemo
{
    public class Billing
    {
        //维护一个算法基类的实例
        BillingAlgorithm billingAlgorithm;

        //简单工厂模式的构造函数
        public Billing(string BillingStrategy)
        {
            switch (BillingStrategy)
            {
                case "打8折":
                    billingAlgorithm = new BillingStrategy_Rebate(0.8);
                    break;
                case "满200返40":
                    billingAlgorithm = new BillingStrategy_CashReturn(200, 40);
                    break;
                default:
                    billingAlgorithm = new BillingStrategy_Rebate(1);
                    break;
            }
        }        //策略模式的构造函数
        public Billing(BillingAlgorithm billingAlgorithm)
        {
            this.billingAlgorithm = billingAlgorithm;
        }
        //这是策略模式的典型特征
        public double GetResult(double price, int quantity)
        {
            return billingAlgorithm.getBillingResult(price, quantity);
        }
    }
}

 好,算法完成了,下面介绍客户端,界面如图2所示:

图2. 商场收银系统界面

 

下面看一下,确定按钮后面的代码:

 

private void button1_Click(object sender, EventArgs e)
        {
            //只需要知道这个Context类,实例化它;
            Billing billing = new Billing(comboBox1.Text);
            //并调用它提供的方法,即可完成我们需要的功能。
            double charge = billing.GetResult(double.Parse(textBox1.Text),
                int.Parse(textBox2.Text));
            string itemShow = "单价:" + textBox1.Text
                + "\t数量:" + textBox2.Text +
                ".\t实收:" + charge.ToString()
                + "\t" + comboBox1.Text;
            listBox1.Items.Add(itemShow);
        }

 转自:http://www.cnblogs.com/colinsong/archive/2009/03/02/1401723.html