设计模式开始--策略模式

时间:2015-03-29 17:43:29   收藏:0   阅读:110

策略模式

作用:

策略模式是一种定义了一系列算法的方法,所有这些算法都是完成相同的工作,只是实现不同,他可以以相同的方式调用所有的算法。策略模式很容易理解,即便没有学习过设计模式,在实际问题也可以想出这种模式来解决问题。

相比工厂模式而言:

类图:

技术分享

实现:

 1、CashSuper算法的形式

技术分享
public abstract class CashSuper {
    public abstract double getCash(double money);
}
View Code

2、三个继承的算法

技术分享
public class CashRebate extends CashSuper {
    private double rebate = 1;
    public CashRebate(double rebate)
    {
        this.rebate = rebate;
    }
    @Override
    public double getCash(double money) {
        // TODO Auto-generated method stub
        return money * rebate;
    }
}
public class CashReturn extends CashSuper {
    private double condition = 0;
    private double moneyReturn = 0;
    public CashReturn(double condition, double moneyReturn)
    {
        this.condition = condition;
        this.moneyReturn = moneyReturn;
    }
    @Override
    public double getCash(double money) {
        if(money >= this.condition)
        {
            money -= Math.floor(money/condition)*moneyReturn;
        }
        return money;
    }
}
public class NormalCash extends CashSuper {
    @Override
    public double getCash(double money) {
        // TODO Auto-generated method stub
        return money;
    }
}
View Code

3、用于实例化算法和调用算法操作的context类

技术分享
public class CashContext {
    CashSuper cs = null;
    public CashContext(String type)
    {
        switch(type)
        {
            case "normal":
                cs = new NormalCash();
                break;
            case "rebate":
                cs = new CashRebate(0.8);
                break;
            case "return":
                cs = new CashReturn(300,80);
                break;
        }
    }
    public double getResult(double money)
    {
        return cs.getCash(money);
    }
}
View Code

4、client类,用于测试

技术分享
public class Client {
    public static void main(String[] args) {
        String type = "return";
        double money = 400;
        CashContext cc = new CashContext(type);
        System.out.println(cc.getResult(money));
    }
}
View Code

 

原文:http://www.cnblogs.com/sunshisonghit/p/4375845.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!