java设计模式-策略模式

什么是策略模式:
策略模式就是处理类型较多,算法比较复杂,代码流程控制比较多,而且难以拓展,这时候,我们就可以使用策略模式了

开发中常用策略模式场景:
1.Spring resouce接口
2.httpservlet中的service接口
3.javase中的gui编程,布局管理

策略模式实现例子:
这里我们实现一个例子,是淘宝商城物品打折,根据用户的不同,打折的算发和策略也不同,我们可以为每个用户量身定做一种算法

/**
 * 策略接口
 * @author liuxg
 * @date 2016年5月27日 下午9:37:20
 */
public interface Strategy {

    double getPrice(double originalPrice);

}


class NewCustomer implements Strategy {


    /**
     * 新顾客策略,是原价
     */
    @Override
    public double getPrice(double originalPrice) {
        System.out.println(originalPrice);
         return originalPrice ;
    }

}
class OrdinaryMember implements Strategy {


    /**
     * 普通会员打8折
     */
    @Override
    public double getPrice(double originalPrice) {
        System.out.println(originalPrice * 0.8);
        return originalPrice * 0.8;
    }

}
 class MasonryMember implements Strategy {

    /**
     * 砖石会员打6折
     */
    @Override
    public double getPrice(double originalPrice) {
        System.out.println(originalPrice * 0.6);
        return originalPrice * 0.6;
    }

}

如果你还有其他的会员需要其他打折算法,你直接写一个类继承即可,客户端我们这样子测试

public class Client {

    public static void main(String[] args) {
        Strategy nc = new NewCustomer();
        Strategy om = new OrdinaryMember();
        Strategy mm = new MasonryMember();

        nc.getPrice(1024.0);
        om.getPrice(1024.0);
        mm.getPrice(1024.0);

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值