On Strategy Strategy Pattern

I. Introduction

What is the strategy pattern?

The word strategy should be how to understand it, so to speak, to go out when we have chosen a different way to travel, such as walking, cycling, bus, train, plane, rocket ride, and so on, these travel modes, each It is a strategy.

Another example is we go to the mall, the mall is now engaged in activities, there is a discount, the full reduction, rebate and so on, in fact, no matter how the mall promotions, in the final analysis are some algorithms that itself is a strategy, and these algorithm is interchangeable at any time possible, such as for the same piece of merchandise, discount of twenty percent today, tomorrow least 100 by 30, among these strategies are interchangeable.

Strategy pattern (Strategy), defines a set of algorithms, each algorithm are packaged together, and the interchangeable therebetween.

Application Second, the strategy pattern

1, When to Use

For business development, the business logic complexity is inevitable, as the business development, the demand will become increasingly complex, in order to take into account a variety of situations, the code will inevitably be a lot of if-else.

Once the code is too much if-else, it will greatly affect its readability and maintainability, and the code is very low.

Strategy pattern perfect solution ifelse troubles!

2, method

These algorithms into a package of a class, or any alternative

3, the advantages

  • Algorithm can freely switch
  • Avoid the use of multiple conditional
  • Scalability is good, just add a strategy to implement the interface

4, shortcomings

  • Strategies will increase the number of classes, each policy is a class, reusability small
  • All classes are required of foreign policy exposed

5, application examples

  • Travel, bicycles, cars, etc., each of which is a way to travel policy
  • Mall promotions, discounts, full reduction, etc.
  • java AWT in LayoutManager, i.e., layout manager

6 Notes

If the policy is a system of more than four, we need to consider the use of problem-solving strategies class mixed-mode expansion

640?wx_fmt=jpeg

Third, to achieve the strategy pattern

Here's to the mall for example the use of promotional strategies to achieve mode algorithm shopping promotions. UML is as follows:

1, the context-based

First, declare a CashSuper object via the constructor, passing specific pricing strategy, function getResult () method to obtain pricing strategy according to different calculations.

package designMode.strategy;

public class CashContext {
    private CashSuper cashSuper;

    public CashContext(CashSuper cashSuper) {
        this.cashSuper = cashSuper;
    }

    public double getResult(double money){
        return cashSuper.acceptCash(money);
    }
}

2. Pay cash abstract class

Policy classes, abstract classes, abstract methods for charging sub-class implementation.

package designMode.strategy;

public abstract class CashSuper {
    public abstract double acceptCash(double money);
}

3, the normal fee subclass

package designMode.strategy;

public class CashNormal extends CashSuper {
    @Override
    public double acceptCash(double money) {
        return money;
    }
}

4, discounted fees subclass

package designMode.strategy;

public class CashRebate extends CashSuper {
    private double moneyRebate = 0.8;

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

    @Override
    public double acceptCash(double money) {
        return money*moneyRebate;
    }
}

5, rebate charges subclass

package designMode.strategy;

public class CashReturn extends  CashSuper {
    private double moneyConditation = 0.0;
    private double moneyReturn = 0.0d;

    public CashReturn(double moneyConditation, double moneyReturn) {
        this.moneyConditation = moneyConditation;
        this.moneyReturn = moneyReturn;
    }

    @Override
    public double acceptCash(double money) {
        double result = money;
        if(money>moneyConditation){
            result = money-Math.floor(money/moneyConditation)*moneyReturn;
        }
        return result;
    }
}

6, client client

package designMode.strategy;

import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        CashContext cashContext = null;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入打折方式(1/2/3):");
        int in = scanner.nextInt();
        String type = "";
        switch (in){
            case 1:
                cashContext = new CashContext(new CashNormal());
                type += "正常收费";
                break;
            case 2:
                cashContext = new CashContext(new CashReturn(300,100));
                type +="满300返100";
                break;
            case 3:
                cashContext = new CashContext(new CashRebate(0.8));
                type += "打八折";
                break;
            default:
                System.out.println("请输入1/2/3");
                break;
        }
        double totalPrices = 0;
        System.out.print("请输入单价:");
        double price = scanner.nextDouble();
        System.out.println("请输入数量:");
        double num = scanner.nextDouble();
        totalPrices = cashContext.getResult(price * num);
        System.out.println("单价:" + price + ",数量:" + num + ",类型:" + type + ",合计:" + totalPrices);
        scanner.close();
    }
}

7, operating results

Fourth, the difference between strategy pattern and engineering mode

1、策略模式是行为性模式,适应行为的变化 ,强调父类的调用子类的特性 。

工厂模式是创建型模式,适应对象的变化,强调统一接口 。

2、策略模式封装行为,调用的时候必须先制定实例化具体的类,再调用抽象的方法; 策略模式的作用是让一个对象在许多行为中选择一种行为。

工厂模式封装对象,实例化对象后调用的时候要知道具体的方法。

3、策略模式是调用不同类方法, 工厂模式是对父类进行重写。

这俩个模式本来就是解决类似的问题,可以说是孪生兄弟,且内部实现都差不多,都是通过子类来覆盖父类而已,不过简单工厂是把父类直接摆在客户端,而策略模式是将父类隐藏在Context里面,这样封装更好。

4、举个例子
(1)产品之于加减乘除,水果之于苹果梨橘子香蕉,文具之于笔尺刀,这时产品比较具体、有限和没有多个算法重叠,这时实用简单工厂模式。
(2)产品之于商场促销中的返利(可为300返100、500返200、10000返500等等无数)、折扣(2折、2.5折、6折、9折、9.1折等等无数)、正常购买、消费积分(100元10积分、200元30积分等等无数),这时产品构造又多次重叠,且有在不同时刻应用不同的规则时使用策略模式。

5、总结

简单工厂模式只是解决了对象的创建问题,工厂需要包括所有的产品对象的创建,如果产品对象形式经常变化,就需要经常改动工厂,以致代码重新编译。所以策略模式就诞生了,策略模式---它定义了算法家族,分别封装起来,而不是像简单产品模式一样定义所有的产品类,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户,使客户拥有相同的访问过程。
简单工厂模式的核心是“简单工厂模式就是用来封装所有的产品对象的”。

策略模式理解核心是“策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中遇到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性”。

在基本的策略模式中,选择所用的具体实现的算法的职责由客户端对象承担,并转给策略模式的Context对象。这是策略模式本身纯粹的定义,所以,“选择所用最终怎样处理”还有很多文章可做。
看了课本之后对于这两个模式还是有很多不理解的地方,但是相信随着对设计模式进一步的学习,能够更好地体会到这其中的奥妙,学习是一个循序渐进的过程。

推荐博客

素小暖讲设计模式

发布了110 篇原创文章 · 获赞 8 · 访问量 6931

Guess you like

Origin blog.csdn.net/guorui_java/article/details/104039882
Recommended