状态模式和策略模式的区别

来源:互联网 发布:数据有效性下拉日期 编辑:程序博客网 时间:2024/06/06 21:38

转自:http://blog.csdn.net/ruangong1203/article/details/52514919


状态模式和策略模式的区别

区别主要体现在行为上,而不是结构上,所以,看时序图就能很好的看出两者的区别。

状态模式

image

看1.4,状态B是状态A创建的,也就是由系统本身控制的。调用者不能直接指定或改变系统的状态转移

所以,状态是系统自身的固有的,调用者不能控制系统的状态转移。比如,一个请假单有“部长审批”-“经理审批”-“审批通过”-“审批不通过”等状态,请假者没有办法将一个部长都还没审批完的请假单提交给经理,这个状态转换只能系统自己完成。

策略模式

image

看1.5,策略B是调用者指定的,系统自身并不能指定或改变策略。

所以策略是外界给的,策略怎么变,是调用者考虑的事情,系统只是根据所给的策略做事情。这时系统很像是一台电脑,根据指令执行动作,打一鞭子滚一滚。

知识检测

小明中国出发到日本再到美国去旅行,在不同的国家都要做两件事,问候和打招呼,怎么做取决于他在哪个国家。(就是编程时经常碰到的多语言问题了)根据需求,请问该使用哪种模式?开发者写了下面的代码,请问下面的代码是状态模式还是策略模式?

public class GreetingContext {    private Country country;    public GreetingContext(Country country){        this.country = country;    }    public void changeCountry(Country country){        this.country = country;    }    public void sayHello(){        country.sayhello();    }    public void greet(){        country.greet();    }}//国家接口public interface Country {    void sayhello();    void greet();}//中国public class China implements Country {    public void sayhello() {        System.out.println("你好!");    }    public void greet() {        System.out.println("握手!");    }}//美国public class America implements Country {    public void sayhello() {        System.out.println("hello!");    }    public void greet() {        System.out.println("kiss");    }}//调用public class Client {    public static void  main(String[] args){        GreetingContext context = new GreetingContext(new China());        context.sayHello();        context.greet();        context.changeCountry(new America());        context.sayHello();        context.greet();    }}

0 0
原创粉丝点击