现在的位置: 首页 > 综合 > 正文

策略模式

2013年08月20日 ⁄ 综合 ⁄ 共 1578字 ⁄ 字号 评论关闭

 

策略模式:
publicinterface Strategy {
    publicdouble calcPrice(double goodsPrice);
}
publicclass NormalCustomerStrategy implements Strategy{
 
    @Override
    publicdouble calcPrice(double goodsPrice) {
       // TODO Auto-generated method stub
       System.out.println("对于新的顾客暂时无折扣.....");
       return goodsPrice;
    }
}
publicclass OldCustomerStrategy implements Strategy {
 
    @Override
    publicdouble calcPrice(double goodsPrice) {
       // TODO Auto-generated method stub
       System.out.println("对于老顾客折扣为5%");
       return goodsPrice*(1-0.05);
    }
}
publicclass LargeCustomerStrategy implements Strategy{
    @Override
    publicdouble calcPrice(double goodsPrice) {
       // TODO Auto-generated method stub
       System.out.println("对于大客户我们的折扣是10%");
       return goodsPrice*(1-0.10);
    }
}
 
publicclass Price {
    private Strategy strategy;
    public Price(Strategy strategy){
       this.strategy=strategy;
    }
    publicdouble quote(double goodsPrice){
       returnthis.strategy.calcPrice(goodsPrice);
    }
}
publicclass Test {
    publicstaticvoid main(String[] args){
       Strategy strategy1=new LargeCustomerStrategy();
       Price p1=new Price(strategy1);
       double quote=p1.quote(1000);
       System.out.println("想客户报价为:"+quote);
       System.out.println("...................");
       Strategy strategy2=new OldCustomerStrategy();
       Price p2=new Price(strategy2);
       double quote1=p2.quote(1000);
       System.out.println("想客户报价为:"+quote1);
       System.out.println("...................");
       Strategy strategy3=new NormalCustomerStrategy();
       Price p3=new Price(strategy3);
       double quote2=p2.quote(1000);
       System.out.println("想客户报价为:"+quote2);
    }
}
运行结果如下:

抱歉!评论已关闭.