Simple strategy pattern example

1. Strategy mode (similar to factory mode)

Write a simple store cash register software; charge users according to the unit price and quantity of the goods purchased by the customer.

It seems simple to multiply two numbers

public class GetTotal {
    
    
    public static double getTotal(double number,double slary) {
    
    
        return number * slary;
    }
}
  • Variation 1: When a discount occurs when joining a shopping mall, the discount is also random. At this time, the above wording will not apply, and it may also be full of activities. We can't always modify the source code.

At this time, we first define a cash charging interface (how the demand changes and the final result does not change)

public interface GetTotal {
    
    
    //公共方法抽离
    double getTotal(double money);
}
//当正常收费的时候
public class CashNormal implements GetTotal {
    
    
    @Override
    public double getTotal(double money) {
    
    
        return money;
    }
}
//当出现打折情况下
public class CashRebate implements GetTotal {
    
    
    private double moneyRebate = 1d;
    
    public CashRebate(double moneyRebate) {
    
    
        this.moneyRebate = moneyRebate;
    }
    @Override
    public double getTotal(double money) {
    
    
        return money * moneyRebate;
    }
}
//当出现满减时
public class CashReturn implements GetTotal {
    
    
    private double moneyCondition = 0.0d;
    private double moneyReturn = 0.0d;
    
    public CashReturn(double moneyCondition, double moneyReturn) {
    
    
        super();
        this.moneyCondition = moneyCondition;
        this.moneyReturn = moneyReturn;
    }

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

}
//定义一个工厂类
public class CashContext {
    
    
    GetTotal testTotal = null;
    public CashContext(String type) {
    
    
        switch (type) {
    
    
            case "正常收费":
                testTotal = new CashNormal();
                break;
            case "满300返100":
                testTotal = new CashReturn(300,100);
                break;
            case "打八折":
                testTotal = new CashRebate(0.8);
                break;
            default:
                break;
        }
    }
    public double getResult(double money) {
    
    
        return testTotal.getTotal(money);
    } 
}

//测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
        CashContext cashContext = new CashContext("正常收费");
    }
}

The essence of the strategy pattern is to separate the public methods of all objects, and achieve different requirements by implementing interface rewriting methods

Guess you like

Origin blog.csdn.net/qq_37771811/article/details/103764377