java设计模式_策略模式

策略模式

    1.概念:

         策略模式是定义了一系列算法的方法和规则,分别封装起来,减少了各种算法类与使用算法之间的耦合。

     2.结构图:

3.实例

/**
 * 收钱的接口(算法接口)
 */
public interface CashSuper {

    public  double acceptCash(Double money);
}

//正常收费

public class Normol implements CashSuper{
    @Override
    public double acceptCash(Double money) {
        return money;
    }
}
/**
 * 打折的情况
 */
public class Disccount implements  CashSuper{
    private Double aDouble=1d;

    public Disccount(String disccount) {
        this.aDouble = Double.parseDouble(disccount);
    }

    @Override
    public double acceptCash(Double money) {
        return money*aDouble;
    }


}

//算法调度类

public class Context {
    CashSuper cashSuper=null;
    public Context(String type){
        switch (type){
            case "正常收费":
                Normol no=new Normol();
                cashSuper=no;
                break;
            case "打折":
                Disccount disccount=new Disccount("0.8");
                cashSuper=disccount;
                break;
        }
    }
    public Double getResult(Double money){
        return cashSuper.acceptCash(money);
    }
}

//测试

public class Test {
    public static void main(String[] args) {
        Context context=new Context("正常收费");
        Context context1=new Context("打折");
       System.out.println( context1.getResult(100.00));


       String Name="com.sw.springboot.test.stratege.Disccount";
        String params="0.8";
        Class[] paramType={String.class};
       ContextReflect contextReflect=new ContextReflect(Name,paramType,params);
        System.out.println( contextReflect.getResult(100.00));

    }

}

策略模式的优点:

(1)策略模式的strategy类层次为contex定义了一系列可重用的算法或行为

(2)策略模式简化了单元测试。因为每个算法都有自己的类可以通过自己的接口测试

(3)策略模式在实践中可以封装几乎任何类型规则。

(4)策略模式与简单模式结合选择具体实现由客户端承担转移到contex减轻了客户端压力

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值