我也设计模式——17.State

状态模式是把各种状态封装成不同的类。



关于Context类的实现,不太同于Strategy,虽然原理是一样的:
    public class Context
    
{
        
private State stateA, stateB, state;

        
public Context()
        
{
            stateA 
= new StateA();
            stateB 
= new StateB();
        }


        
public void Request(int temp)
        
{
            
if (temp > 0)
                state 
= stateA;
            
else
                state 
= stateB;

            state.Handle();
        }

    }
可以看到,Request()方法是基于简单工厂的。
还有,Context的ctor是基于单件模式的,可以使用注册工厂来简化。

在Client端的调动方式,就这么简单:
            Context context = new Context();
            context.Request(
20);


基于委托的状态模式
委托部分:

    public delegate void state();

    
public class ContextUseingDelegate
    
{
        
public state myState;

        
public void ContextInterface()
        
{
            myState();
        }

    }

我们需要在Context类中使用委托,而在Client端不变:

    public class Context
    
{
        
public void Request(int temp)
        
{
            ContextUseingDelegate cud 
= new ContextUseingDelegate();

            
if (temp > 0)
            
{
                StateA sa 
= new StateA();
                cud.myState 
+= new state(sa.ConcreteStateA);
            }

            
else
                cud.myState 
+= new state(StateB.ConcreteStateB);

            cud.ContextInterface();
        }

    }

 

posted @ 2007-10-04 11:41 包建强 阅读(77) 评论(0)  编辑 收藏 所属分类: Design Patterns

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2007-10-26 16:07 编辑过


相关链接: