Design Patterns - Strategy Pattern

1. What is the strategy pattern

  It is to define a set of algorithms, each algorithm to the package together, they can call each other, and can be interchanged between them; This mode allows the algorithm change will not affect customers using the algorithm.

  * Core strategy model is the packaging of the algorithm, the ultimate goal is to shift the responsibility (environment) using an algorithm and implementation of algorithms coupled.

2. Strategy mode advantages and disadvantages:

 (1) Advantages

      - switching algorithm can be freely carried out

      - Avoid multiple determination conditions (reducing the number of objects), reduces the complexity and redundancy of the program codes.

      - scalability is very good

     - policy class to provide a way can replace inheritance

     - through the interface and

(2) disadvantages

     - an increase in the number of policies like more complicated.

     - all policy classes need of external exposure, the more exposure, the greater the risk is modified later, the client must know that all of the strategies and means that the user must understand the difference between each of these algorithms, select the appropriate strategies and methods . (Flyweight may be used to reduce the number of objects).

 

3. The implementation of the strategy pattern

* Environment (Context) role, holds one, and maintaining Strategy object references, and decided to call the kind of Strategy Role complete business logic.

* Abstract Strategy (Strategy) defines a common interface for all supported algorithms are the core, summed up the strategy pattern algorithm, it is a consistent external interface.

* Specific strategies (ConcreteStrategy) encapsulates a specific algorithm or behavior, inherited Strategy

 

 

4. The specific operation mode strategy

(Take a mall cash register system as an example)


        double total = 0.0d;     //total来计算总计

        private void BtnOk_Click(object sender, EventArgs e)
        {
            double totaprices = Convert.ToDouble(txtPrice.Text) * 
        Convert.ToDouble(txtNum.Text);  //购买商品总价

            //把商品价钱计入总计。
            total = total + totaprices;
            //列表框中显示信息。
            lbxList.Items.Add("单价:" + txtPrice.Text + "数量:" + txtNum.Text+"合计:" + 
        totaprices.ToString());  

        }

  But if you write it like this go, if you want to increase the discount shopping then how to do?

 

Simple factory pattern implementation:

Let's write the parent class a normal fee, and then subclasses that implements multiple discounts and rebates, the use of polymorphic method to accomplish this code.

  * CashSuper: parent

  * CashNormal: no discount

  * CashRebate: Discount

  * CashReturn: rebate

  With this simple model plant, three subclasses can be encapsulated to random switching, (parent class are inherited CashSuper) premise.

//现金收费抽象类
    abstract class Cashsuper
    {
        public abstract double AcceptCash(double money);
    }

    class CashNormal : Cashsuper   //正常收费子类
    {
        public override double AcceptCash(double money)    //正常收费,原价返回
        {
            return money;
        }
    }

    class CashRebate : Cashsuper   //正常收费类
    {
        private double moneyRebate = 1d;

        public CashRebate(string moneyRebate)
        {
            this.moneyRebate = double.Parse(moneyRebate);
        }

        public override double AcceptCash(double money)
        {
            return money * moneyRebate;
        }

    }

    //返利类
    class CashReturn : Cashsuper
    {
        private double moneyCondition = 0.0d;   //返利的条件
        private double moneyReturn = 0.0d;   //返利值

        public CashReturn(string moneyCondition, string moneyReturn)
        {
            this.moneyCondition = double.Parse(moneyCondition);
            this.moneyReturn = double.Parse(moneyReturn);
        }
        public override double AcceptCash(double money)
        {
            double result = money;
            if (money >=moneyCondition)
            {
                result = money - Math.Floor(money / moneyCondition) * moneyReturn;
            }

            return result;

        }

    }

    //现金收费工厂
    class CashFactory
    {
        public static Cashsuper createCashAccept(string type)
        {
            Cashsuper cs = null;
            switch (type)
            {
                case "正常收费":
                    cs = new CashNormal();
                    break;
                case "满300返100":
                    CashReturn cr1 = new CashReturn("300", "100");
                    cs = cr1;
                    break;
                case "打八折":
                    CashRebate cr2 = new CashReturn("0.8");
                    cs = cr2;
                    break;
            }
            return cs;


        //客户端代码
        double total = 0.0d;     //total来计算总计

        private void btnOk_Click(object sender, EventArgs e)
        {
            Cashsuper csuper = new CashContext(cbxType.SelectedItem.Tostring());
            CashFactory.createCashAccept(cpxtype.SelectedItem.ToString());
            double totalPrices = 0d;

            totalPrices = csuper.AcceptCash(Convert.ToDouble(txtPrice.Text)) * 
            Convert.ToDouble(txtNum.Text);
            total = total + totalPrices;
            lbxList.Items.Add("单价:" + txtPrice.Text + "数量:" + txtNum.Text + "" + 
            cbxtype.selectedItem + "合计:" + totalPrices.ToString());

            lblresult.Text = total.ToString();

        }

Strategy pattern combined with a simple plant:


        //客户端代码
        double total = 0.0d;     //total来计算总计

        private void btnOk_Click(object sender, EventArgs e)
        {
            Cashsuper csuper = new CashContext(cbxType.SelectedItem.Tostring());
            CashFactory.createCashAccept(cpxtype.SelectedItem.ToString());
            double totalPrices = 0d;

            totalPrices = csuper.AcceptCash(Convert.ToDouble(txtPrice.Text)) * 
            Convert.ToDouble(txtNum.Text);
            total = total + totalPrices;
            lbxList.Items.Add("单价:" + txtPrice.Text + "数量:" + txtNum.Text + "" + 
            cbxtype.selectedItem + "合计:" + totalPrices.ToString());

            lblresult.Text = total.ToString();

        }

 

Guess you like

Origin blog.csdn.net/M_hcCSDN/article/details/94358970