Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1680383
  • 博文数量: 210
  • 博客积分: 10013
  • 博客等级: 上将
  • 技术积分: 2322
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-25 15:56
文章分类

全部博文(210)

文章存档

2011年(34)

2010年(121)

2009年(37)

2008年(18)

我的朋友

分类: Java

2011-03-18 18:18:51

package com.utstar.pattern.strategy;

/**
 * 策略算法统一接口
 * @author HZ20232
 *
 */

public interface Strategy {
    public double calculate(double old);
}


package com.utstar.pattern.strategy;

/**
 * 策略算法的一个实现
 * @author HZ20232
 *
 */

public class NormalCustomer implements Strategy{
    
    public double calculate(double old){
        System.out.println("普通用户一律99折");
        return old*0.99;
    }
}


package com.utstar.pattern.strategy;
/**
 * 另一个实现
 * @author HZ20232
 *
 */

public class OldCustmer implements Strategy{
    public double calculate(double old){
        System.out.println("老用户一律5折");
        return old*0.5;
    }
}


package com.utstar.pattern.strategy;

public class BigCustmer implements Strategy{
    public double calculate(double old){
        System.out.println("大客户一律1折");
        return old*0.1;
    }
}


package com.utstar.pattern.strategy;

/**
 *
 * @author HZ20232
 *
 */

public class Price{
    private Strategy method;
    
    public Price(Strategy s){
        this.method = s;
    }
    public void setMethod(Strategy s){
        this.method = s;
    }
    public double getPrice(double old){
        return this.method.calculate(old);
    }
}


package com.utstar.pattern.strategy;

/**
 * 策略模式,当ifelse比较多的时候可以考虑用策略模式,其各种策略算法是平行关系,没有归属关系
 * java是面向接口编程,在考虑设计的时候优先考虑接口,其次当有对公用功能进行规定的时候考虑抽象类
 * @author HZ20232
 *
 */

public class TestStrategy{
    public static void main(String args[]){
        Strategy normal = new NormalCustomer();
        
        Price context = new Price(normal);
        double old = 100;
        double normalPrice = context.getPrice(old);
        System.out.println(normalPrice);
        
        Strategy oldCustmer = new OldCustmer();
        
        context.setMethod(oldCustmer);
        double oldPrice = context.getPrice(old);
        System.out.println(oldPrice);
        
        Strategy bigCustmer = new BigCustmer();
        
        context.setMethod(bigCustmer);
        double bigPrice = context.getPrice(old);
        System.out.println(bigPrice);
    }
}


阅读(1173) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~