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
Structural diagram:
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(); } }
Define a flying Interface:
/** * 策略接口:实现了鸭子的飞行行为 */ public interface Flying { void Fly(); }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("我会飞");
}
}
public class FlyNoWay implements Flying {
@Override
public void Fly() {
System.out.println("我不会飞行");
}
}
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("我是红色的鸭子");
}
}
/**
*
* 绿色鸭子
*/
public class GreenDuck extends duck{
public GreenDuck(){
super();
//给鸭子注入飞行的能力,这里也是通过算法族里面的会飞的算法
super.setFlying(new FlyWithWin());
}
@Override
public void display() {
System.out.println("我是绿色的鸭子");
}
}
/**
* 小鸭子,还不会飞
*/
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("嘎~嘎~嘎");
}
}
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("***测试完毕***");
}
}
##***Test duck program***
I am a red duckQuackI can fly
When using the mallard duck as the object:
***Test completed***
***测试鸭子程序*** 我是绿色的鸭子 嘎嘎嘎 我会飞 ***测试完毕***When using the little duck as the object When object:
***Test duck program***
I am still a little duckqua~qua~qua1. When a system needs to dynamically choose one of several algorithms, each The algorithm is encapsulated into a strategy class2. 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 replaced3. 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 customersI can’t fly
* **Test completed***
5. Application scenarios of strategy mode
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.