当前位置: 移动技术网 > IT编程>开发语言>Java > ·java设计模式--策略模式

·java设计模式--策略模式

2019年06月21日  | 移动技术网IT编程  | 我要评论

策略模式:定义了不同的算法,分别分装起来,让他们可以互相替换,即使算法变化了,也不会影响到使用算法的用户

首先定义一个抽象算法类,有两个类继承了这个抽象类,重写了algorithminterface()方法

public abstract class strategy {

    public abstract void  algorithminterface();

}

public class algorithma extends strategy {
    @override
    public void algorithminterface() {
        system.out.println("实现算法a");
    }
}

public class algorithmb extends strategy {
    @override
    public void algorithminterface() {
        system.out.println("实现算法b");
    }
}

用一个context类来维护对抽象算法类strategy对象的引用(重点)

public class context {
    strategy strategy;
    public context(strategy strategy){
        this.strategy = strategy;
    }

    public void contrxtinterface(){
        strategy.algorithminterface();
    }
}

测试类1

public class test1 {
    public static void main(string[] args) {
        context context = null;
        context = new context(new algorithma());
        context.contrxtinterface();

        context = new context(new algorithmb());
        context.contrxtinterface();

    }
}

 

但是从上面测试类1的代码我们发现是在客户端判断是用什么算法,现在我们想把这个判断交由其他类处理,于是就有了下面的策略模式与简单工厂结合的方法。

 

public class context2 {
    strategy strategy = null;

    public context2(string type){
        switch (type){
            case "a": strategy = new algorithma();
            break;
            case "b": strategy = new algorithmb();
            break;

        }
    }
    public void contrxtinterface(){
        strategy.algorithminterface();
    }
}

测试类2

public class text2 {
    public static void main(string[] args) {
        context2 context2a = new context2("a");
        context2a.contrxtinterface();
        context2 context2b = new context2("b");
        context2b.contrxtinterface();
    }
}

 

结论:策略模式定义一系列算法,他们完成的都是同一件事,只是实现方法不同,比如超市收银时,会员打折,非会员不打折,实现的都是收钱,实现方法(打折/非打折)不同。

优点:1.上下文和具体策略是松耦合关系。因此上下文只知道它要使用某一个实现strategy接口类的实例,但不需要知道具体是哪一个类。

2.策略模式满足“开-闭原则”。当增加新的具体策略时,不需要修改上下文类的代码,上下文就可以引用新的具体策略的实例。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网