• java设计模式--行为型模式--状态模式


    什么是行为型模式,小编觉得就是对行为的一种描述啦,一种对某种行为模型的定义。

    状态模式:

        

     1                                                     状态模式
     2  概述
     3     定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
     4  
     5  
     6  适用性
     7     1.一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为。
     8 
     9     2.一个操作中含有庞大的多分支的条件语句,且这些分支依赖于该对象的状态。
    10       这个状态通常用一个或多个枚举常量表示。
    11       通常,有多个操作包含这一相同的条件结构。
    12       State模式将每一个条件分支放入一个独立的类中。
    13       这使得你可以根据对象自身的情况将对象的状态作为一个对象,这一对象可以不依赖于其他对象而独立变化。
    14  
    15  
    16  参与者
    17     1.Context
    18       定义客户感兴趣的接口。
    19       维护一个ConcreteState子类的实例,这个实例定义当前状态。
    20 
    21     2.State
    22       定义一个接口以封装与Context的一个特定状态相关的行为。
    23 
    24     3.ConcreteStatesubclasses
    25       每一子类实现一个与Context的一个状态相关的行为。

    测试代码:

      

     1 public class Test{
     2 
     3     public static void main(String[] args) {
     4         Context ctx1 = new Context();
     5         ctx1.setWeather(new Sunshine());
     6         System.out.println(ctx1.weatherMessage());
     7 
     8         System.out.println("===============");
     9 
    10         Context ctx2 = new Context();
    11         ctx2.setWeather(new Rain());
    12         System.out.println(ctx2.weatherMessage());
    13     }
    14 }
    1 public interface Weather {
    2 
    3     String getWeather();
    4 }
     1 public class Context {
     2 
     3     private Weather weather;
     4 
     5     public void setWeather(Weather weather) {
     6         this.weather = weather;
     7     }
     8 
     9     public Weather getWeather() {
    10         return this.weather;
    11     }
    12 
    13     public String weatherMessage() {
    14         return weather.getWeather();
    15     }
    16 }
    1 public class Sunshine implements Weather {
    2 
    3     public String getWeather() {
    4         return "阳光";
    5     }
    6 }
    1 public class Rain implements Weather {
    2 
    3     public String getWeather() {
    4         return "下雨";
    5     }
    6 }

    说明:一个状态中传入什么具体实现就是什么实现啦。。。感觉这种实现模型挺牛。不停明白中....

     

    来一篇比较好理解的链接博文:http://men4661273.iteye.com/blog/1633973

  • 相关阅读:
    DeflateStream类
    BufferedStream类
    FileStream类
    Asp.net MVC Comet 推送
    MVC 读书笔记
    MVC部署
    MVC系统过滤器、自定义过滤器
    MVC 路由规则
    MVC 模型绑定
    边双+点双模板
  • 原文地址:https://www.cnblogs.com/huzi007/p/3985633.html
Copyright © 2020-2023  润新知