[Design Mode]-Strategy Mode

1. Introduction to Strategy Mode

1. What is the strategy mode

The Strategy Pattern is also called the **Policy Pattern** that defines the algorithm groups and encapsulates them separately so that they can be replaced with each other so that the algorithm changes will not affect the users who use the algorithm. The strategy mode is a behavioral design mode. In the strategy mode, the behavior and algorithm of a class can be changed at runtime.

2. When can the strategy mode be used

The strategy mode is usually applied in the following scenarios:

  1. Eliminate code complexity and maintenance problems caused by if-else
  2. The application is only slightly different in algorithm and behavior among multiple classes
  3. Scenarios that need to be implemented by the shielding algorithm
  4. Freely switch between algorithms

2. Business scenario analysis strategy mode

1. Business scenario

I think that some theoretical changes cannot help you understand the concept of design patterns very well. On the contrary, it is easy to hypnotize you. So when I talk about design patterns, I am used to using actual business scenarios to talk about the application and implementation of this thing. Today we will use one of the most common usage scenarios of the strategy mode: promotional activities to see how the strategy mode is applied.

A well-known fresh food platform held a year-end promotional event near the New Year, including meat products over 100 minus 20 yuan, vegetable products over 50 minus 15 and cooked food products over 100 minus 10 yuan. After learning about the promotion and interaction, Xiaolong ordered 123 yuan of meat products, 53 yuan of vegetable products and 140 yuan of cooked food products on the fresh food platform. Please calculate how much Xiaolong has to pay in the end?

2. Business realization without strategy mode

If we do not adopt the strategy model , we may think of the first time is to distinguish product types through a simple if-else, and then calculate the discount amount. So let's see how to implement it in the previous way and analyze the advantages and disadvantages of this code:

Step 1: Create an order interface

public interface Order {
    
    
// 计算优惠
	Long calculate();
}

Step 2: Create meat, vegetables, and cooked food orders

public class MeatOrder implements Order{
    
    

	// 订单总金额
	private Long totalAmount;

	// 实际支付金额
	private Long realAmount;

	public Long calculate() {
    
    
		if (totalAmount >= 10_000) {
    
    
			realAmount = totalAmount - 2000;
		} else {
    
    
			realAmount = totalAmount;
		}
		return realAmount;
	}

	public MeatOrder(Long totalAmount) {
    
    
		super();
		this.totalAmount = totalAmount;
	}
}

public class VegetablesOrder implements Order {
    
    

	// 订单总金额
	private Long totalAmount;

	// 实际支付金额
	private Long realAmount;

	public Long calculate() {
    
    
		if (totalAmount >= 5000) {
    
    
			realAmount = totalAmount - 1500;
		} else {
    
    
			realAmount = totalAmount;
		}
		return realAmount;

	}

	public VegetablesOrder(Long totalAmount) {
    
    
		super();
		this.totalAmount = totalAmount;
	}

}
// 熟食订单
public class CookedFoodOrder implements Order {
    
    

	// 订单总金额
	private Long totalAmount;

	// 实际支付金额
	private Long realAmount;

	public Long calculate() {
    
    
		if (totalAmount >= 10_000) {
    
    
			realAmount = totalAmount - 1000;
		} else {
    
    
			realAmount = totalAmount;
		}
		return realAmount;

	}

	public CookedFoodOrder(Long totalAmount) {
    
    
		super();
		this.totalAmount = totalAmount;
	}

}

Step 3: Create the cash register

public class Cashier {
    
    

	public static void main(String[] args) {
    
    
		MeatOrder meatOrder = new MeatOrder(123 * 100l);
		VegetablesOrder vegetablesOrder = new VegetablesOrder(53 * 100l);
		CookedFoodOrder cookedFoodOrder = new CookedFoodOrder(140 * 100l);
		// 收银
		List<Order> list = new ArrayList<>();
		list.add(meatOrder);
		list.add(vegetablesOrder);
		list.add(cookedFoodOrder);
		Long cashier = cashier(list);
		System.out.println("您一共消费"+(cashier / 100) + "元");

	}

	/**
	 * @Title: cashier
	 * @Description: TODO
	 *
	 */
	private static Long cashier(List<Order> list) {
    
    
		Long amount = 0l;
		for (Order order : list) {
    
    
			Long calculate = order.calculate();
			amount += calculate;
		}
		return amount;
	}
}

Let's analyze the advantages and disadvantages of this code:
First of all, we can see that this code uses Java's own polymorphism to implement its own full reduction algorithm in each order class. The advantage of this writing method is that it is simple to implement, which many students can imagine. The second is that the amount of code is small and the development workload is not large. So are there any disadvantages in this way of writing? of course! The dynamic expansion ability of this writing method is very poor. If we put forward new requirements at this time:

After New Year's Day, the fresh food platform decided to restore the original price

Then we think about what we are going to do at this time?
Insert picture description here
The easiest way is definitely to directly delete the part about full reduction in the above code. But this is undoubtedly a violation of the opening and closing principle in the JAVA design specification. In the case of business changes, we should be open to expansion, closed to changes, and direct code modification is not allowed. So what should we do in this situation?

3. Implementation of Strategy Mode

The strategy mode is designed for this kind of business scenario that often changes. Here I first provide a strategy pattern code implementation, and later analyze how this code is designed.

3.1 The first step is to create a policy definition interface

public interface FullReduction {
    
    
	Long reduction(Long amount);
}

3.2 Create a strategy to implement the interface

public class MeatReduction implements FullReduction {
    
    

	@Override
	public Long reduction(Long amount) {
    
    
		if (amount >= 10_000) {
    
    
			return amount - 2000;
		} else {
    
    
			return amount;
		}
	}

}
public class CookedFoodReduction implements FullReduction {
    
    

	@Override
	public Long reduction(Long amount) {
    
    
		if (amount >= 10_000) {
    
    
			return amount - 1000;
		} else {
    
    
			return amount;
		}
	}

}

3.3 Create Strategy Usage Class

public class Order {
    
    

	private FullReduction reduction;

	private Long amount;

	public Order(FullReduction reduction, Long amount) {
    
    
		super();
		this.reduction = reduction;
		this.amount = amount;
	}

	public Long count() {
    
    
		return reduction.reduction(amount);
	}

}

3.4 Create cash register

public class Cashier {
    
    

	public static void main(String[] args) {
    
    
		List<Order> list = new ArrayList<Order>();
		list.add(new Order(new MeatReduction(), 124 * 100l));
		list.add(new Order(new CookedFoodReduction(), 140 * 100l));
		list.add(new Order(new VegetablesReduction(), 53 * 100l));
		Long amount = count(list);
		System.out.println("您消费总金额为:" + (amount / 100) + "元");
	}

	/**
	 * @Title: count
	 * @Description: TODO
	 *
	 */
	private static Long count(List<Order> list) {
    
    
		Long amount = 0l;
		for (Order order : list) {
    
    
			amount += order.count();
		}
		return amount;
	}
}

operation result:
Insert picture description here

4. Through the business analysis of the advantages and disadvantages of the strategy model

We can simply analyze some characteristics of the strategy mode by comparing the above codes;
advantages:

  1. Strategy mode can replace inheritance relationship and reduce inheritance through aggregation.
  2. Strategy mode can reduce redundant if-else judgment code blocks. The corresponding algorithm can be used through algorithmic decision-making.
  3. The strategy mode meets the requirements of the opening and closing principle. For expansion and opening, new strategies will not affect existing strategies.

Disadvantages:

  1. The client must know all the strategies and decide which strategy to use.
  2. Strategy mode will generate many strategy classes, increasing the number of objects.

Three, the strategy pattern in Java

1. The design ideas of the strategy model

If you read the above code and still have questions, I think it is normal, because although the above strategy mode provides code, the design ideas of the whole mode are not explained in detail. Here first draw a composition diagram of the strategy mode to let everyone further understand the strategy mode.

Insert picture description here
In fact, the strategy model is very simple:

  1. The first step: first create a policy constraint interface to restrict what behaviors the desired policy requires.
  2. Step 2: Create an implementation class for the strategy interface, and add an implementation class for each new strategy.
  3. The third step: Create a Context selection combiner that references the strategy to implement the combination of strategy and business.
  4. Step 4: Specify the strategy required by the business in the program.

2. Strategy mode in JDK

2.1 Comparator interface

The most typical implementation of the strategy interface in Java is the Comparator interface. The sort method in the Comparator interface provides different sorting strategies for different types of objects. If we want to implement the sorting of a custom object, we need to pass a sorting rule for the custom object, which is the implementation of the Comparator interface. Here I post a piece of Arrays to implement the source code of the sort method in the comparator for the friends to analyze.
Insert picture description here

Four, summary

1. Features of the strategy mode:

advantage:

  1. Strategy mode can replace inheritance relationship and reduce inheritance through aggregation.
  2. Strategy mode can reduce redundant if-else judgment code blocks. The corresponding algorithm can be used through algorithmic decision-making.
  3. The strategy mode meets the requirements of the opening and closing principle. For expansion and opening, new strategies will not affect existing strategies.

Disadvantages:

  1. The client must know all the strategies and decide which strategy to use.
  2. Strategy mode will generate many strategy classes, increasing the number of objects.

2. Use scenarios of strategy mode

  1. Only behave differently between multiple entities
  2. A system needs to dynamically choose among multiple algorithms.

3. Problems solved by the strategy model

1. Decoupling : The strategy mode perfectly supports the "opening and closing principle". Users can choose the implementation method without modifying the original basic system, or can flexibly add new implementations. Simply put, the addition and change of one algorithm will not affect other algorithms.
2. Effective management of implementation classes : Provides a variety of management methods for the implementation of the same interface. Due to the existence of a policy management role, the specific policy role invocation methods are concentrated.
3. Replace the inheritance relationship : Provides a way to replace the inheritance relationship.
4. Replace multiple conditional transfers : Avoid using multiple conditional transfer statements.

Okay, that's it for today's content. I hope that the rewarding friends can make three connections with one click! Refusal of prostitution starts with me.

Guess you like

Origin blog.csdn.net/xiaoai1994/article/details/112266997