Design Patterns (1) - strategists mode

Address reprint article:  https://www.jianshu.com/p/3bcf55cf83d3

First, the business scenario:

       1, there is a bird, bird common attributes, such as flying and called, different sounds, you can subclass the parent class is rewritten, when the property business expansion, as well as birds eat,

     However, different birds, eat something different, like on some class, this method does not require, how to solve it? a. subclass overrides the superclass method, but when there are multiple classes implemented,

     Modify too much trouble, b. Define a unified interface to eat, eat different foods ways to achieve a unified interface to eat, when to eat different kinds of birds, calling different implementation classes to achieve different

    The birds eat different ways;

  2, when an old class, you need to add a method in the main class, subclass inherits after all, will call this method, but not all subclasses need to implement this method, this time we need to think of new ways a:

    1 ), in each sub-category in this new way to rewrite --- "too much trouble, and the code reusability is not high,

    2 ) to define a behavior ( interface ), the specific implementation of behavior is not the same, the inclusion of a duck call: Gaga called, gugu called, concrete subclasses to implement the behavior is not the same, the ultimate expression of the way is not the same

 Second, 类图

 

Third, to achieve the common code:

class Client {
     public  static  void main (String [] args) {
         // select a particular policy 
        IStrategy Strategy = new new ConcreteStrategyA ();
         // to a context of 
        the Context context = new new the Context (Strategy);
         // client directly from the context algorithm execution environment 
        context.algorithm (); 
    } 

    // abstract strategy strategy 
    interface IStrategy {
         void algorithm (); 
    } 

    // DETAILED strategy ConcreteStrategy 
    static  class ConcreteStrategyA the implements IStrategy {

        @Override
        public void algorithm() {
            System.out.println("Strategy A");
        }
    }

    //具体策略类 ConcreteStrategy
    static class ConcreteStrategyB implements IStrategy {

        @Override
        public void algorithm() {
            System.out.println("Strategy B");
        }
    }

    //上下文环境
    static class Context {
        private IStrategy mStrategy;

        public Context(IStrategy strategy) {
            this.mStrategy = strategy;
        }

        public void algorithm() {
            this.mStrategy.algorithm();
        }
    }
}

 

Strategists realize arithmetic mode, avoid using if..else ... and so bring out the code redundancy

Mode 

Whyn 

concern 

appreciate the support 
strategy mode
 0.723 
2018.10.27 23:31:27 
Word Count 1093 
Reading 4496 
Profile 
Define a family of algorithms, encapsulate each one, and make them interchangeable. 
Define a set of algorithms, each algorithm are packaged together, and so you can swap between them. 

Strategy Mode (Strategy Pattern) mode, also known as Policy (Policy Pattern). It refers to an object with a behavior, but in a different scenario, the act has a different algorithm. For example, a person's tax rate related to his salary, the different wage levels corresponding to different tax rates. 

Strategy mode is used object-oriented inheritance and polymorphism mechanisms to achieve the same behavior with different implementations in different scenarios. 

Strategy Pattern nature: separation algorithm, choose to implement 

the main solution 
in a variety of algorithms similar cases, the use IF ... the else or Switch ... Case complexity and cumbersome nature brings. 

Disadvantages 
advantages 

algorithm diversity, and have free switching function; 
effectively avoid multiple conditional, enhanced encapsulation, simplifying the operation, reducing the probability of errors;
Good scalability, the substitution principle policy class compliance Xu Richter can be easily carried Policy extension; 
drawback of 

increasing the number of policy class, and all policy class must be of external exposure, so that clients can select; 
use scenarios 
for the same type of problem, there are a variety of treatments, each of which can independently solve problems; 
algorithm needs the freedom to switch the scene; 
scene requires masking algorithm rules; 
model to explain 
first of all look at the strategy pattern generic UML class diagram: 

strategy pattern 
UML class diagram from we can see that the strategy pattern contains three main roles: 

context roles (context): change in strategy for operating context, the shield layer module (client) direct access to the strategy, algorithm, the package may be present; 
abstract strategy role (strategy): acts specified strategy or algorithm; 
specific strategies roles (ConcreteStrategy): specific strategies or algorithms; 
the following is a generic code the strategy pattern: 

class Client {
     public  static  void main (String [] args) {
         / / select a specific strategy 
        IStrategy at strategy = new new to a contextConcreteStrategyA ();
         // 
        the Context context = new new the Context (Strategy);
         // client algorithm executed directly from the context 
        context.algorithm (); 
    } 

    // abstract Strategy Strategy 
    interface IStrategy {
         void algorithm (); 
    } 

    // specific strategy ConcreteStrategy 
    static  class ConcreteStrategyA the implements IStrategy { 

        @Override 
        public  void algorithm () { 
            System.out.println ( "A strategy" ); 
        } 
    } 

    // DETAILED strategy ConcreteStrategy
     static  classConcreteStrategyB the implements IStrategy { 

        @Override 
        public  void algorithm () { 
            System.out.println ( "Strategy B" ); 
        } 
    } 

    // context 
    static  class the Context {
         Private IStrategy mStrategy; 

        public the Context (IStrategy Strategy) {
             the this .mStrategy = Strategy ; 
        } 

        public  void algorithm () {
             the this .mStrategy.algorithm (); 
        } 
    } 
}
举个例子
Example: Suppose there are two numbers with an operator, require the operator to operate the two numbers. 
Analysis: Direct ideas:, these two numbers is determined by performing calculation operator symbols. Code as follows: 

    static  class the Calculator {
         Private  static  Final String SYMBOL_ADD = "+" ;
         Private  static  Final String SYMBOL_SUB = "-" ; 

        public  int Calc ( int A, int B, Final String Symbol) {
             int Result = 0 ;
             IF (SYMBOL_ADD.equals (Symbol)) { 
                Result = A + B; 
            } the else  IF (SYMBOL_ADD.equals (Symbol)) {
                Result = A - B; 
            } 
            return Result; 
        } 
    } 
but this write, if we want to extend multiplication * or division / operation, it will increase in the corresponding calc method determines if ... else, and extension code bloat too low. 
If using policy mode, calculates various operators are integrated into the corresponding specific policy, so the code can be simplified and brings very good scalability, specific code as follows: 

class Client {
     public  static  void main (String [] args) { 
        the ICalculator Calculator = new new the Add (); 
        the context context = new new the context (Calculator);
         int Result = context.calc (1,2  );
        System.out.println (Result); 
    } 

    interface ICalculator {
        int calc(int a, int b);
    }

    static class Add implements ICalculator {
        @Override
        public int calc(int a, int b) {
            return a + b;
        }
    }

    static class Sub implements ICalculator {
        @Override
        public int calc(int a, int b) {
            return a - b;
        }
    }

    static class Multi implements ICalculator {
        @Override
        public int calc(int a, int b) {
            return a * b;
        }
    }

    static class Divide implements ICalculator {
        @Override
        public int calc(int a, int b) {
            return a / b;
        }
    }

    static class Context {
        private ICalculator mCalculator;

        public Context(ICalculator calculator) {
            this.mCalculator = calculator;
        }

        public int calc(int a, int b) {
            return this.mCalculator.calc(a, b);
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/liweiweicode/p/11570550.html