Lying design pattern ------ strategy mode

Strategy Mode (strategy): It defines a family of algorithms, encapsulate them, so that they can replace each other, this mode allows the algorithm change does not affect customers using the algorithm.

 

 

 

public abstract class CashSuper {
public abstract double acceptCash(double money);
}
/**
* 正常收费子类
*/
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
/**
* 打折收费子类
*/
public class CashRebate extends CashSuper {

private double moneyRebate;

public CashRebate(double moneyRebate){
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
/**
* 返现收费子类
*/
public class CashReturn extends CashSuper {
private double moneyCondition;
private double moneyReturn;

public CashReturn(double moneyCondition, double moneyReturn) {
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}

@Override
public double acceptCash(double money) {
if(money >= moneyCondition){
return money - Math.floor( money / moneyCondition ) * moneyReturn;
}
return 0;
}
}

import lombok.Data;

@Data
public class CashContext {

CashSuper cashSuper;

public CashContext(String type){
switch (type){
case "正常收费" :
cashSuper = new CashNormal();
break;
case "满300返100" :
cashSuper = new CashReturn(300,100);
break;
case "打8折" :
cashSuper = new CashRebate(0.8);
break;
}
}

public double getResult(double money){
return cashSuper.acceptCash(money);
}
}

public class TestCash {
@Test
public void test2() {
CashContext cashContext = new CashContext("打8折");
double cash = cashContext.getResult(3000);
System.out.println(cash);
}
}

Strategy Pattern Analysis:

  Strategy Mode is a way to define a series of algorithms, from the conceptual point of view, all of these algorithms are identical to complete the work, but to achieve different, it can call all the algorithms in the same way, reducing the variety of classes and algorithms using a coupling between classes.

  advantage:

   1. The test unit is simplified, since each class has its own algorithm, can be tested individually by their interfaces;

   2. The strategy pattern is used to encapsulate the algorithm, but in practice, it can be almost any type of packaging rules, whenever they hear the different needs at different times of the application of business rules, you can consider using strategy pattern in the analysis process to deal with this possibilities change.

The above code is not perfect, the best way is to implement with reflection condition selected. . .

Guess you like

Origin www.cnblogs.com/zsmcwp/p/11615653.html