Dahua Design Pattern--Strategist Pattern

 In business requirements, there will be an identical result, but with a different algorithm. For example, discounts in shopping malls result in discounts on products, but the discount methods are different. Algorithms are different. Therefore, it is necessary to use the strategist pattern, encapsulate these algorithms with classes, build a simple factory, and then use a context class to communicate with the client. Such as:

package effective.Strategist;

public class CashContext {
	private CashSuper cash;//A class with the same abstract behavior
	
	public  CashContext(CashSuper cashSuper){
		this.cash=cashSuper;
	}
	public double getResult(double money){
		return cash.acceptCash(money);
	}
	public static void main(String[] args) {
		CashContext cc = null;
		String aa = "1";//For example, this is the request parameter received by the client
		switch(aa){
		case "1": cc = new CashContext(new CashRebute());//Different implementations of the same behavior
		case "2": cc = new CashContext(new CashReturn());
		case "3": cc = new CashContext(new CashNormal());
		}
	}
}
The advantage of this is that during processing, the client only needs to follow
It is enough to communicate with CashContext, without interacting with the three subclasses of CashSuper. thus reducing the coupling

Guess you like

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