The Strategy Pattern of Dahua Design Patterns

background:

During the promotion period of shopping malls, there may be 20% off, 50% off promotional activities, and there may also be promotional activities of 10% off over 100 and 30% off over 200. Design a cash register system.

Strategy mode: defines a family of algorithms so that they can be replaced with each other. This mode allows changes in the algorithm to not affect the customers who use the algorithm.

UML class:

Demo:

Algorithm interface Strategy:

1 public interface Strategy {
2 
3     void algorithmInterface();
4 }

The specific algorithm ConcreteStrategyA:

1 public class ConcreteStrategyA implements Strategy {
2     @Override
3     public void algorithmInterface() {
4         System.out.println("算法A实现");
5     }
6 }

The specific algorithm ConcreteStrategyB:

1 public class ConcreteStrategyB implements  Strategy {
2     @Override
3     public void algorithmInterface() {
4         System.out.println("算法B实现");
5     }
6 }

Context context class:

 1 public class Context {
 2 
 3     private Strategy stagtegy;
 4 
 5     public Context(String algorithm) {
 6         switch (algorithm){
 7             case "A":stagtegy = new ConcreteStrategyA();break;
 8             case "B":stagtegy = new ConcreteStrategyB();break;
 9             default:break;
10         }
11     }
12 
13     public void contextInterface(){
14         stagtegy.algorithmInterface();
15     }
16 }

Test class:

1 public class Main {
2 
3     public static void main(String[] args) {
4         Context context = new Context("A");
5         context.contextInterface();
6     }
7 }

Summarize:

The strategy pattern is commonly used in daily development. The usage scenario is: an interface or abstract class has a set of specific implementations, and abstract methods in the interface or abstract class are used when using, so that different strategies can be implemented according to different incoming instances. For example, you can pass the above Strategy as a parameter to a method.

Guess you like

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