@ Chapter 25 design patterns: Strategy pattern

Chapter 25: Strategy Mode

First, write a duck project, specific requirements are as follows:

  • There are a variety of ducks (such as duck, Beijing duck, teal and other ducks have all kinds of behavior, such as call, flying, etc.)

  • Displays information Ducks

Second, the traditional solution to the problem of ducks analysis and code implementation

  • Traditional design (FIG class)

  • Code implementation - see the teacher demonstrate

Duck abstract class

package com.gjxaiou.strategy;

public abstract class Duck {

    public Duck() {
    }

    public abstract void display();//显示鸭子信息
    
    public void quack() {
        System.out.println("鸭子嘎嘎叫~~");
    }
    
    public void swim() {
        System.out.println("鸭子会游泳~~");
    }
    
    public void fly() {
        System.out.println("鸭子会飞翔~~~");
    }
}

Duck specific class

package com.gjxaiou.strategy;

public class PekingDuck extends Duck {

    @Override
    public void display() {
        System.out.println("~~北京鸭~~~");
    }
    
    //因为北京鸭不能飞翔,因此需要重写fly
    @Override
    public void fly() {
        System.out.println("北京鸭不能飞翔");
    }
}

//-------------------------------------------------------
package com.gjxaiou.strategy;

public class ToyDuck extends Duck{

    @Override
    public void display() {
        System.out.println("玩具鸭");
    }

    //需要重写父类的所有方法
    @Override
    public void quack() {
        System.out.println("玩具鸭不能叫~~");
    }
    
    @Override
    public void swim() {
        System.out.println("玩具鸭不会游泳~~");
    }
    
    @Override
    public void fly() {
        System.out.println("玩具鸭不会飞翔~~~");
    }
}

//-------------------------------------------------------------
package com.gjxaiou.strategy;

public class WildDuck extends Duck {

    @Override
    public void display() {
        System.out.println(" 这是野鸭 ");
    }
}

use

package com.gjxaiou.strategy;

public class Client {

    public static void main(String[] args) {
        //测试
    }
}

Third, the problem of the traditional manner of analysis and solutions

  • Other Duck, Duck class are inherited, so all subclasses will fly to fly, this is not true

  • Question 1 above said, in fact, is the question of succession to bring: local changes, especially involving the superclass of local changes will affect other parts. There will be spillover effects

  • In order to improve a problem, we can be solved by covering fly method => coverage resolved

  • The question again, if we have a toy duck ToyDuck, which will require ToyDuck to cover Duck methods all implemented => Corrections - " policy mode (strategy pattern)

Fourth, the strategy pattern basic introduction

  • Strategy Mode (Strategy Pattern), the definition of family of algorithms (policy group) were encapsulated, so that they can replace each other, this mode lets the algorithm vary independently of the use of algorithms customer households

  • This algorithm embodies several design principles, first, the change of the code separated from the constant code; second, rather than a specific programming interface for the class (the policy defines the interface); and third, the use of the combination / polymerization less inheritance (customer usage policies by combination).

Figure V class principle, the strategy pattern

Note: You can see from the chart, there are members of the client context variable strategy or other strategies interfaces, as to which strategy is required, we can specify in the constructor

Sixth, the strategy pattern to solve the problem of ducks

  • Examples of application requirements

Preparation procedures are completed in front of the duck project, requires the use of the Strategy pattern

  • Thought analysis (FIG class)

Strategy Mode: encapsulate the behavior of the interface, algorithm family, put the superclass behavior interface object, the object of conduct set in concrete subclass. Principle is: change in the separation portion, the package interface, a programming interface based on the various functions. This mode allows the behavior of the algorithm change is independent of the user

  • Code

    Duck abstract class

package com.gjxaiou.strategy.improve;

public abstract class Duck {

    //属性, 策略接口
    FlyBehavior flyBehavior;
    //其它属性<->策略接口
    QuackBehavior quackBehavior;
    
    public Duck() {
    }

    public abstract void display();//显示鸭子信息
    
    public void quack() {
        System.out.println("鸭子嘎嘎叫~~");
    }
    
    public void swim() {
        System.out.println("鸭子会游泳~~");
    }
    
    public void fly() {
        //改进
        if(flyBehavior != null) {
            flyBehavior.fly();
        }
    }

    public void setFlyBehavior(FlyBehavior flyBehavior) {
        this.flyBehavior = flyBehavior;
    }
    
    public void setQuackBehavior(QuackBehavior quackBehavior) {
        this.quackBehavior = quackBehavior;
    }
}

Specific entity class

package com.gjxaiou.strategy.improve;

public class PekingDuck extends Duck {
    
    //假如北京鸭可以飞翔,但是飞翔技术一般
    public PekingDuck() {
        flyBehavior = new BadFlyBehavior();
    }
    
    @Override
    public void display() {
        System.out.println("~~北京鸭~~~");
    }
}

//----------------------------------------------
package com.gjxaiou.strategy.improve;

public class ToyDuck extends Duck{
    
    public ToyDuck() {
        flyBehavior = new NoFlyBehavior();
    }
    
    @Override
    public void display() {
        System.out.println("玩具鸭");
    }

    //需要重写父类的所有方法
    @Override
    public void quack() {
        System.out.println("玩具鸭不能叫~~");
    }
    
    @Override
    public void swim() {
        System.out.println("玩具鸭不会游泳~~");
    }
}

//--------------------------------------------------
package com.gjxaiou.strategy.improve;

public class WildDuck extends Duck {
    
    //构造器,传入FlyBehavor 的对象
    public  WildDuck() {
        flyBehavior = new GoodFlyBehavior();
    }
    
    @Override
    public void display() {
        System.out.println(" 这是野鸭 ");
    }
}

Flight behavior abstract and entity classes

package com.gjxaiou.strategy.improve;

public interface FlyBehavior {
    
    void fly(); // 子类具体实现
}

//----------------------------------------------
package com.gjxaiou.strategy.improve;

public class GoodFlyBehavior implements FlyBehavior {

    @Override
    public void fly() {
        System.out.println(" 飞翔技术高超 ~~~");
    }
}

//---------------------------------------------
package com.gjxaiou.strategy.improve;

public class BadFlyBehavior implements FlyBehavior {

    @Override
    public void fly() {
        System.out.println(" 飞翔技术一般 ");
    }
}

//------------------------------------------------------
package com.gjxaiou.strategy.improve;

public class NoFlyBehavior implements FlyBehavior{

    @Override
    public void fly() {
        System.out.println(" 不会飞翔  ");
    }
}

use

package com.gjxaiou.strategy.improve;

public class Client {

    public static void main(String[] args) {
        WildDuck wildDuck = new WildDuck();
        wildDuck.fly();//
        
        ToyDuck toyDuck = new ToyDuck();
        toyDuck.fly();
        
        PekingDuck pekingDuck = new PekingDuck();
        pekingDuck.fly();
        
        //动态改变某个对象的行为, 北京鸭 不能飞
        pekingDuck.setFlyBehavior(new NoFlyBehavior());
        System.out.println("北京鸭的实际飞翔能力");
        pekingDuck.fly();
    }
}

Seven Strategies pattern analysis in the application source JDK-Arrays

  • Comparator Arrays of the JDK on the use of the Strategy pattern

  • Source code analysis + + Debug mode analysis role

  • Code

Eight, notes and details of the strategy pattern

  • Mode key strategies are: analysis of the project in part with the same part of the change

  • The core idea of ​​the strategy pattern is: the use of combination / aggregation less inheritance; combination of inherited behavior categories, rather than behavior. More flexible

  • The concept of "closed for modification, to expand open" principle, increase client behavior without modifying the existing code, just add a strategy (or behavior) to avoid the use of multiple branch statement (if..else if..else )

  • Can provide a way to replace inheritance: Strategy pattern algorithm will make your package in a separate Strategy classes can be independent of its Context change it, make it easy to switch, easy to understand, easy to expand

  • Note that : Each time you add a policy would add a class, when the strategy will lead to excessive number of classes Pang

Guess you like

Origin www.cnblogs.com/qq438649499/p/12178441.html