admin 管理员组文章数量: 1184232
23种设计模式
1 Strategy定义
Strategy 策略模式是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类。
策略模式简单来说就是将一个对象的多个具体策略进行独立封装起来,彼此之间可进行替换。
2 如何使用?
举例:超市买了本书“架构设计师”66元,不同会员的折扣是不同的;不同的结算方式就相当于一个一个策略;
package xx.study.design.strategy;
import java.math.BigDecimal;
/**
* 收银员
*/
public class StrategyDemo {
private Customer customer;
private BigDecimal cost(BigDecimal oldCost) {
return customer.cost(oldCost);
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public static void main(String[] args) {
StrategyDemo cashier = new StrategyDemo();
CommonCustomer commonCustomer = new CommonCustomer();
SuperVipCustomer superCustomer = new SuperVipCustomer();
VipCustomer vipCustomer = new VipCustomer();
//买了本书“架构设计师” 花了66元
BigDecimal bigDecimal = new BigDecimal(66);
//调用不同算法
cashier.setCustomer(commonCustomer);
System.out.printf("普通用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
cashier.setCustomer(vipCustomer);
System.out.printf("vip用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
cashier.setCustomer(superCustomer);
System.out.printf("超级vip用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
}
}
package xx.study.design.strategy;
import java.math.BigDecimal;
/**
* 策略接口
*/
public interface Customer {
/**
* 计算折扣后的花费
* @param oldCost 原花费
* @return 折扣后的花费
*/
public BigDecimal cost(BigDecimal oldCost);
}
package xx.study.design.strategy;
import java.math.BigDecimal;
/**
* 可以看成一个一个策略封装
*/
public class CommonCustomer implements Customer {
@Override
public BigDecimal cost(BigDecimal oldCost) {
return oldCost.multiply(new BigDecimal(0.8));
}
}
package xx.study.design.strategy;
import java.math.BigDecimal;
public class VipCustomer implements Customer {
@Override
public BigDecimal cost(BigDecimal oldCost) {
return oldCost.multiply(new BigDecimal(0.7));
}
}
package xx.study.design.strategy;
import java.math.BigDecimal;
public class SuperVipCustomer implements Customer {
@Override
public BigDecimal cost(BigDecimal oldCost) {
return oldCost.multiply(new BigDecimal(0.6));
}
}
版权声明:本文标题:设计模式之 Strategy(策略)通俗理解 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1754914714a3049609.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论