概述
今天接着学习设计模式,今天要学习的模式是策略模式。PS: 最近有点懈怠了。沉迷于业务代码不能自拔,自己的学习进程被中断了,实在是不应该。闲话不多说,我们接着看看策略模式。
引子
一个比较典型的策略模式的应用场景是:商场的促销活动,不同的促销活动我们可以编写不同的算法。
定义与结构
策略模式:它定义了算法族,分别封装起来,让它们之间可以互相替换。此模式让算法的变化,不会影响到使用算法的客户。
类图
我们来看看具体的demo
Strategy抽象策略接口类
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public abstract class Strategy {
/**
* 抽象的算法
*/
public abstract void algorithmlnterface();
}
Context 上下文类
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void contextInterface() {
strategy.algorithmlnterface();
}
}
具体策略类
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public class ConcreteStrategyA extends Strategy {
public void algorithmlnterface() {
System.out.println("具体策略A");
}
}
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public class ConcreteStrategyB extends Strategy {
public void algorithmlnterface() {
System.out.println("具体策略B");
}
}
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public class ConcreteStrategyC extends Strategy {
public void algorithmlnterface() {
System.out.println("具体策略C");
}
}
客户端Client类
package com.strategy;
/**
* Created by xiang.wei on 2018/4/18
*
* @author xiang.wei
*/
public class Client {
public static void main(String[] args) {
Context contextA = new Context(new ConcreteStrategyA());
contextA.contextInterface();
Context contextB = new Context(new ConcreteStrategyB());
contextB.contextInterface();
Context contextC = new Context(new ConcreteStrategyC());
contextC.contextInterface();
}
}