Home > Java > javaTutorial > body text

How to implement Java's strategy pattern using code

王林
Release: 2023-05-18 17:49:34
forward
1477 people have browsed it

    Strategy Pattern

    The strategy pattern is one of the 23 behavioral patterns in Java. Let’s first look at what the strategy pattern is.

    1. What is the Strategy Pattern

    Definition of the Strategy Pattern:

    This design pattern encapsulates a series of algorithms so that they can be replaced with each other. The algorithm changes will not affect client usage. The strategy pattern belongs to the object behavior pattern. It encapsulates the algorithm, separates the responsibility for using the algorithm from the implementation of the algorithm, and delegates the management of these algorithms to different objects.

    In fact, we often encounter situations in real life where there are multiple strategies to choose from to achieve a certain goal. For example, when traveling, you can take a plane, take a train, ride a bicycle, or drive your own private car. Or for example, for online shopping, you can choose Industrial and Commercial Bank of China, Agricultural Bank of China, China Construction Bank, etc., but the algorithms they provide are all the same, which is to help you pay.

    We will also encounter similar situations in software development. When there are multiple algorithms or strategies to implement a certain function, we can choose different algorithms or strategies to complete the function according to different environments or conditions. Function.

    2. Advantages and disadvantages of strategy mode

    Advantages:

    • ##Multiple conditional statements are difficult to maintain, but using strategy mode can Avoid using multiple conditional statements

    • Through inheritance, the public code of the algorithm family can be placed in the parent class to avoid code reuse and provide a series of reusable algorithms

    • Provides different implementations of the same behavior. Customers can choose different ones according to different time or space requirements.

    • Provides perfect support for the opening and closing principle, You can flexibly add new algorithms without modifying the original code, put the use of algorithm

    • into the environment class, and move the implementation of the algorithm into the specific strategy class, achieving two goals. Separation of operators

    Disadvantages:

    • The client must understand the difference between all strategy algorithms in order to choose the appropriate one at the right time Algorithm class

    • The strategy model creates many strategy classes, which increases the difficulty of maintenance

    3. The structure of the strategy model

    1 .Abstract strategy class: defines a public interface. Different algorithms implement this interface in different ways. Environmental roles use this interface to call different algorithms, generally using interfaces or abstract classes.

    2. Specific strategy class: implements the interface defined by the abstract strategy and provides specific algorithm implementation.

    3. Environment class: holds a reference to a strategy class, which is ultimately called by the client.

    Structural diagram:

    How to implement Javas strategy pattern using code

    4. Code implementation

    Now there are three ducks: Green duck, red duck, little duck (little duck can't fly yet)

    Now define a parent class of duck: There are methods for barking and appearance. Method (because each one is different, it needs to be rewritten by subclasses)

    It can also fly

    (strategy mode is used here)

    public  abstract class duck {
        //鸭子都会叫:
        public void quack(){
            System.out.println("嘎嘎嘎");
        }
        //鸭子的外观,因为都不一样,所以由子类去实现
        public abstract void display();
    	
    	//以下使用策略模式:
        //在父类中持有该接口,并由该接口代替飞行行为(组合)
        private Flying flying;
        //提供set方法
        public void setFlying(Flying flying) {
            this.flying = flying;
        }
        public void fly(){
            flying.Fly();
        }
    }
    Copy after login

    Define a flying Interface:

    /**
     * 策略接口:实现了鸭子的飞行行为
     */
    public interface Flying {
        void Fly();
    }
    Copy after login

    We know that the strategy mode is to encapsulate the algorithm that needs to be used, and we encapsulate the

    flying and ## in another package Two methods of #Cannot Fly:

    Can fly (inherited to the above flight interface, override the flight method):

    public class FlyWithWin implements Flying {
        @Override
        public void Fly() {
            System.out.println("我会飞");
        }
    }
    Copy after login

    Can't fly:

    public class FlyNoWay implements Flying {
        @Override
        public void Fly() {
            System.out.println("我不会飞行");
        }
    }
    Copy after login

    Note:

    I encapsulate the above two methods separately as an algorithm family, and then when the program needs to use one of the algorithms, The program will not be affected by algorithm changes, because the final effect of the algorithm is the same

    Red Feathered Duck:

    /**
     * 红色鸭子
     */
    public class RedDuck extends duck{
        public RedDuck(){
            super();
            //给鸭子注入飞行的能力,这里就是通过算法族里面的会飞的算法
            super.setFlying(new FlyWithWin());
        }
        @Override
        public void display() {
            System.out.println("我是红色的鸭子");
        }
    }
    Copy after login

    Green Feathered Duck:

    /**
     *
     * 绿色鸭子
     */
    public class GreenDuck extends duck{
        public GreenDuck(){
            super();
            //给鸭子注入飞行的能力,这里也是通过算法族里面的会飞的算法
            super.setFlying(new FlyWithWin());
        }
        @Override
        public void display() {
            System.out.println("我是绿色的鸭子");
        }
    }
    Copy after login

    Little duck type (cannot fly):

    /**
     * 小鸭子,还不会飞
     */
    public class SamllDuck extends duck{
        public SamllDuck(){
            super();
            //小鸭子不会飞,所以使用了算法族里面不会飞的算法
            super.setFlying(new FlyNoWay());
        }
    
        @Override
        public void display() {
            System.out.println("我还是小鸭子");
        }
        //因为小鸭子和大鸭子的叫声不一样,所以重写叫声方法
        public void quack(){
            System.out.println("嘎~嘎~嘎");
        }
    }
    Copy after login

    Test type:

    public class Test {
        public static void main(String[] args) {
            System.out.println("***测试鸭子程序***");
            duck d = null;
    		//这下面是轮流运行!!!!  
            d = new RedDuck();  //测试红色的鸭子
            d = new GreenDuck();  //测试绿色的鸭子
            d = new SamllDuck();  //测试小鸭子
            d.display();
            d.quack();
            d.fly();
            System.out.println("***测试完毕***");
        }
    }
    Copy after login

    When using the red duck as the object:

    ##***Test duck program***

    I am a red duck
    Quack

    I can fly
    ***Test completed***


    When using the mallard duck as the object:

    ***测试鸭子程序***
    我是绿色的鸭子
    嘎嘎嘎
    我会飞
    ***测试完毕***
    Copy after login
    When using the little duck as the object When object:

    ***Test duck program***

    I am still a little duck
    qua~qua~qua

    I can’t fly
    * **Test completed***


    5. Application scenarios of strategy mode

    1. When a system needs to dynamically choose one of several algorithms, each The algorithm is encapsulated into a strategy class

    2. A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class. Each conditional branch can be moved into their respective In the strategy class, these conditional statements can be replaced

    3. When the algorithms in the system are completely independent of each other, and the implementation details of specific algorithms are required to be hidden from customers

    4. When the system requires that customers using the algorithm should not know the data they operate on, the strategy pattern can be used to hide the data structures related to the algorithm

    5. The only difference between multiple classes is their different performance behaviors. You can use the strategy pattern to dynamically select specific behaviors to be executed at runtime

    The above is the detailed content of How to implement Java's strategy pattern using code. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!