策略模式

来源:互联网 发布:淘淘商城 源码 2016 编辑:程序博客网 时间:2024/05/07 19:56

策略模式(Strategy):它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户.

下面是代码的类图:

这里写图片描述

Strategy

/** 策略类,定义所有支持的算法的公共接口 */public interface Strategy {    void AigorithmInterface();}

StrategyA

public class StrategyA implements Strategy {    public void AigorithmInterface() {        System.out.println("我是策略A实现");    }}

StrategyB和StrategyC类似

Context

public class Context {    private Strategy strategy;    public void ContextInterface() {        strategy.AigorithmInterface();    }    public void setStrategy(Strategy strategy) {        this.strategy = strategy;    }}

测试类:

public class Test {    public static void main(String[] args) {        Context context = new Context();        context.setStrategy(new StrategyA());        context.ContextInterface();    }}

策略模式是一种定义了一系列算法的方法,所有算法完成的都是类似的工作.使用策略模式可以减少使用算法的类和算法之间的耦合.

如果使用依赖注入,完全可以在配置文件中控制具体使用哪一个策略.不用改动代码.极大的降低了耦合度.

0 0
原创粉丝点击