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

    xiaoxiao2021-03-25  98

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

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

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

    状态模式

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

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

    策略模式

    看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(); } }
    转载请注明原文地址: https://ju.6miu.com/read-18166.html

    最新回复(0)