策略模式

策略模式:定义一组算法,将每个算法都封装起来,并且使它们之间可以互换.

举个栗子:我们网购下单的时候,可以选择多种支付方式,如支付宝,网银,微信等,那么支付方式就是一组算法.

代码清单-1 支付策略

/**
 * 支付策略
 */
public interface PayStrategy {
    /** 支付方法 */
    void pay();
}

代码清单-2 微信支付

/**
 * 微信支付方式
 */
public class WeiXinPayStrategy implements PayStrategy {

    public void pay() {
        System.out.println("正在使用微信支付方式...");
    }
}

代码清单-3 支付宝支付

/**
 * 支付宝支付方式
 */
public class AlipayStrategy implements PayStrategy{

    public void pay() {
        System.out.println("正在使用支付宝支付方式...");
    }
}

代码清单-4 网银支付

/**
 * 网银支付方式
 */
public class CyberBankPayStrategy implements PayStrategy {

    public void pay() {
        System.out.println("正在使用网银支付方式...");
    }
}

代码清单-5 消费者

public class Custom {

    public void buy(){
        System.out.println("已购买一双袜子,准备去支付...");
    }
    /** 可以支持多种支付方式 */
    public void pay(PayStrategy payStrategy){
        payStrategy.pay();
    }
}

代码清单-6 场景类

public class Client {
    public static void main(String[] args) {
        Custom custom = new Custom();
        custom.buy();
        //此处可以更换多种支付方式
        PayStrategy weixinPay = new WeiXinPayStrategy();
        custom.pay(weixinPay);
    }
}

运行结果

已购买一双袜子,准备去支付...
正在使用微信支付方式...

  

posted @ 2016-07-14 22:14  Keeper丶  阅读(180)  评论(0编辑  收藏  举报