State状态模式

参考于下面的链接:
http://www.jdon.com/designpatterns/designpattern_State.htm
http://blog.csdn.net/qutr/archive/2006/08/01/1007617.aspx

State模式的定义 : 不同的状态,不同的行为;或者说,每个状态有着相应的行为.

何时使用  State模式在实际使用中比较多,适合"状态的切换".

来段代码:

//先来一个状态:
package State;

public abstract class State
{
    
    /** *//** Creates a new instance of State */
    public State() {
    }
    
    public abstract void opration(Context context);
}//end class State

//在来两个具体的State:
public class ConcreteStateA extends State
{
    
    /** *//** Creates a new instance of ConcreteStateA */
    public ConcreteStateA() {
    }

    public void opration(Context context)
    {
        System.out.println("The Concrete A");
        context.setSate(new ConcreteStateB());
    }//end opration()
    
    public static ConcreteStateA getInstance()
    {
        return new ConcreteStateA();
    }//end getInstance()
}

public class ConcreteStateB extends State
{
    
    /** *//** Creates a new instance of ConcreteStateB */
    public ConcreteStateB() {
    }

    public void opration(Context context)
    {
        System.out.println("The Concrete B");
        context.setSate(new ConcreteStateA());
    }//end opration()
    
    public static ConcreteStateB getInstance()
    {
        return new ConcreteStateB();
    }//end getInstance()
    
}//end class ConcreteStateB

//来一个场景:
public class Context
{
    private State state;
    /** *//** Creates a new instance of Context */
    public Context() {
    }
    
    public void setSate(State stat)
    {
        state = stat;
    }//end setState()
    
    public void operation()
    {
        state.opration(this);
    }//end operation()
    
}//end class Context

//怎样调用:
public static void main(String[] args)
{
		Context con = new Context();
		con.setSate(ConcreteStateA.getInstance());
		con.operation();
		con.operation();
}//end main()
 

以上代码摘自上面介绍的blog中,不过有部分改动。下面是UML图 也是盗链的。。。。。

State模式

你可能感兴趣的:(.net,工作,Blog,UML)