zoukankan      html  css  js  c++  java
  • state pattern

    更多内容参考 :

    http://www.programcreek.com/2011/07/java-design-pattern-state/

    state设计模式主要是为了在运行时改变状态。

    下面是一个例子:

    人们可以生活在不同的经济条件下,可以是富有 ,也可以是穷。两种状态可以相互转换。例子背后的想法是:

    当人们穷的时候,他们更努力的 工作,当人们富有的时候,他们玩的多。他们做什么由他们的生活水平决定。他们的状态也可以由他们做

    什么来改变。否则 ,这个社会就是不公平的。

    State pattern class diagram 

    可以和strategy进行对比。

    首先是state classes 

    package statepattern;
    
    public interface State {
    	public void saySomething ( StateContext sc );
    
    }
    
    class Rich implements State{
    
    	public void saySomething(StateContext sc) {
    		System.out.println("i am rich and play a lot");
    		sc.changeState(new Poor()) ;
    	}
    	
    }
    
    class Poor implements State{
    
    	public void saySomething(StateContext sc) {
    		System.out.println("i am poor and work a lot");
    		sc.changeState(new Rich()) ;
    	}
    	
    }
    

      

     然后是stateContext

    package statepattern;
    
    public class StateContext {
    	private State currentState ;
    	
    	public StateContext(){
    		currentState = new Poor() ;
    	}
    	public void changeState(State newState){
    		this.currentState = newState ;
    	}
    	public void saySomething (){
    		this.currentState.saySomething(this) ;
    	}
    }
    

    最后是测试代码 

    package statepattern;
    
    public class TestMain {
    	public static void main(String [] args){
    		StateContext sc = new StateContext() ;
    		
    		sc.saySomething() ;
    		sc.saySomething() ;
    		sc.saySomething();
    		sc.saySomething() ;
    	}
    }
    

      

  • 相关阅读:
    C++引用小结
    C++关于const的使用以及理解
    python购物车程序的简单程序优化版
    C++文件操作
    python购物车简单小程序
    python学习DAY3(列表)
    C++重载双目运算符(2)(对象与数之间)
    C++重载双目运算符(1)(对象与对象之间)
    C++重载单目运算符
    Elasticsearch 添加数据
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4461838.html
Copyright © 2011-2022 走看看