zoukankan      html  css  js  c++  java
  • 我也设计模式——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();
            }

        }
  • 相关阅读:
    RGB空间与HSV空间的相互转换(C++实现,修正网上大多数的代码错误)
    SLIC superpixel实现分析
    开发自己PHP MVC框架(一)
    C++ 直方图匹配算法代码
    准确率与召回率
    Github干货系列:C++资源集合-
    ezw证件照芯片压缩算法
    格拉姆-施密特正交化
    [轉]sendpage漏洞分析 CVE-2009-2692
    ptrace
  • 原文地址:https://www.cnblogs.com/Jax/p/913948.html
Copyright © 2011-2022 走看看