状态模式

设计模式的意义在于:面向业务内容、业务数据结构和系统架构,高内聚低耦合、优雅的将平面逻辑立体化。

 1 package designPattern;
 2 /**
 3  * 状态模式
 4  * @author Administrator
 5  */
 6 public class C22_StateTest {
 7 
 8     /**
 9      *  定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
10      *    适用于: 
11      *    1.一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为。
12      *    2.一个操作中含有庞大的多分支的条件语句,且这些分支依赖于该对象的状态。
13      *  这个状态通常用一个或多个枚举常量表示。
14      *     通常,有多个操作包含这一相同的条件结构。
15      *  State模式将每一个条件分支放入一个独立的类中。
16      *  这使得你可以根据对象自身的情况将对象的状态作为一个对象,这一对象可以不依赖于其他对象而独立变化。
17      */
18     public static void main(String[] args) {
19         Context1 ctx1 = new Context1();
20         ctx1.setWeather(new Sunshine());
21         System.out.println(ctx1.weatherMessage());
22 
23         System.out.println("===============");
24 
25         Context1 ctx2 = new Context1();
26         ctx2.setWeather(new Rain());
27         System.out.println(ctx2.weatherMessage());
28     }
29 }
30 //context
31 class Context1 {
32 
33     private Weather weather;
34 
35     public void setWeather(Weather weather) {
36         this.weather = weather;
37     }
38 
39     public Weather getWeather() {
40         return this.weather;
41     }
42 
43     public String weatherMessage() {
44         return weather.getWeather();
45     }
46 }
47 //state
48 interface Weather {
49 
50     String getWeather();
51 }
52 //concreteState
53 class Rain implements Weather {
54 
55     public String getWeather() {
56         return "下雨";
57     }
58 }
59 class Sunshine implements Weather {
60 
61     public String getWeather() {
62         return "阳光";
63     }
64 }

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:http://files.cnblogs.com/files/xiluhua/designPattern.rar

欢迎亲们评论指教。

原文地址:https://www.cnblogs.com/xiluhua/p/4413823.html