策略模式是用來封裝算法,封裝變化的,只在咱們在分析業務的時候出如今不一樣的時間段使用不一樣的業務邏輯,就能夠考慮使用策略模式java
package com.design.design.strategy;
/**
* @author zhaozha
* @date 2019/11/3 上午9:32
*/
public class Constant {
public static final int JAVA_SALARY_INCENTIVE = 10;
public static final int PHP_SALARY_INCENTIVE = 1;
}
複製代碼
package com.design.design.strategy;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import java.math.BigDecimal;
/**
* @author zhaozha
* @date 2019/11/3 上午9:17
*/
@Data
@Builder
@AllArgsConstructor
@RequiredArgsConstructor
public class Salary {
private int day;
private BigDecimal datPay;
}
複製代碼
package com.design.design.strategy;
import java.math.BigDecimal;
/**
* @author zhaozha
* @date 2019/11/4 下午8:33
*/
public abstract class BaseSalaryCalculation {
/**
* 計算月薪
*
* @param salary 計費對象
*/
public abstract BigDecimal getSalary(Salary salary);
}
複製代碼
package com.design.design.strategy;
import java.math.BigDecimal;
import static com.design.design.strategy.Constant.JAVA_SALARY_INCENTIVE;
/**
* @author zhaozha
* @date 2019/11/3 上午9:14
*/
public class JavaSalaryCalculation extends BaseSalaryCalculation {
/**
* JAVA激勵10天
*
* @param salary 計費對象
* @return 月薪
*/
@Override
public BigDecimal getSalary(Salary salary) {
return salary.getDatPay().multiply(new BigDecimal(salary.getDay() + JAVA_SALARY_INCENTIVE));
}
}
複製代碼
package com.design.design.strategy;
import java.math.BigDecimal;
import static com.design.design.strategy.Constant.PHP_SALARY_INCENTIVE;
/**
* @author zhaozha
* @date 2019/11/3 上午9:15
*/
public class PHPSalaryCalculation extends BaseSalaryCalculation {
/**
* PHP激勵1天
*
* @param salary 計費對象
* @return 月薪
*/
@Override
public BigDecimal getSalary(Salary salary) {
return salary.getDatPay().multiply(new BigDecimal(salary.getDay() + PHP_SALARY_INCENTIVE));
}
}
複製代碼
package com.design.design.strategy;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author zhaozha
* @date 2019/11/4 下午8:33
*/
@Slf4j
public class SalaryContext {
BaseSalaryCalculation baseSalaryCalculation = null;
public SalaryContext(Class c) {
try {
baseSalaryCalculation = (BaseSalaryCalculation) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public BigDecimal getSalary(Salary salary) {
// 抽取公共部分,如記個日誌
log.info("計算時間:{}",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
return baseSalaryCalculation.getSalary(salary);
}
}
複製代碼
package com.design.design.strategy;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
/**
* @author zhaozha
* @date 2019/11/4 下午8:39
*/
@Slf4j
public class Test {
public static void main(String agrs[]) {
SalaryContext salaryContext = new SalaryContext(JavaSalaryCalculation.class);
Salary salary = Salary.builder().day(10).datPay(new BigDecimal("10")).build();
log.info("JAVA工資:{}",salaryContext.getSalary(salary));
}
}
複製代碼