Strategies of twenty-three design patterns in Java

First, the strategy pattern is a wrapper around the algorithm.

Secondly, the strategy pattern consists of 3 parts:
 * 1. Interface/abstract class: Declare the algorithm (strategy)
 * 2. Implementation class: Implement the above interface. Provide different specific strategies
 * 3. Environment: There are three fixed contents in Context :
 * 1. The interface declaration is used as a member variable, indicating that the current context has a strategy
 * 2. Which strategy to use is determined by the set method

 * 3. Call the method in the strategy. Get the result.

Below, an example is used to illustrate the strategy pattern:

       Example: Use the strategy pattern and Lambda anonymous function to implement a simple calculator function:

    First, we wrap the addition, subtraction, multiplication, and division algorithms:

public interface Calc {
    /**
     * Computational behavior
     * @param num1 value 1
     * @param num2 value 2
     * @return result
     */
    double operator(double num1,double num2);
    /**
     * 4 inner classes to implement different strategies.
     */
    class Add implements Calc{

        @Override
        public double operator(double num1, double num2) {
            return num1 + num2;
        }
    }
    class Sub implements Calc{

        @Override
        public double operator(double num1, double num2) {
            return num1 - num2;
        }
    }

    class Mul implements Calc{

        @Override
        public double operator(double num1, double num2) {
            return num1 * num2;
        }
    }

    class Div implements Calc{
        @Override
        public double operator(double num1, double num2) {
            return num1 / num2;
        }
    }
}

Next write the test class:

public class Test {

    /**
     * Declare the strategy to be used here
     */
    Calc mCalc;

    /**
     * Customize which strategy to use.
     * @param calc
     */
    public void setCalc(Calc calc) {
        this.mCalc = calc;
    }

    /**
     * The result obtained by the algorithm encapsulated by the strategy.
     * @return
     */
    public double calcResult(){
        return mCalc.operator(1,2);
    };

    public static void main(String [] args){
        //-- Static access non-static needs to be accessed through the object
        Test t = new Test();
        //-- set policy
        // The class file generated after the inner class is compiled is the outer class $inner class.
        // If it is an anonymous inner class, the class file is the outer class $1.class
        t.setCalc(new Calc.Div());
        //-- Calculation results
        System.out.println(t.calcResult());


    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324708661&siteId=291194637