状态变化模式

2016-10-04  本文已影响35人  timber_wu

在组件构建过程中,某些对象的状态经常面临变化,如何对这些变化进行有效的管理?同时又维持高层模块的稳定?“状态变化”模式为这一问题提供了一种解决方案。

典型模式

State状态模式

动机

模式定义

允许一个对象在其内部状态改变时改变它的行为。从而使对象看起来似乎修改了其行为。

结构

类图

模式中的角色:

状态模式的代码演示

    import sun.security.krb5.internal.NetClient;
    public abstract class NetworkState{
    
        public NetworkState next;//指针,指向下一状态
    
        public abstract void Operation1();
        public abstract void Operation2();
        public abstract void Operation3();
    / /抽象出三个方法
    }
    
    public class OpenState extends NetworkState{
    
    
        @Override
        public void Operation1(){
            
            //**********
            next = new CloseState();
        }
    
        @Override
        public void Operation2(){
            
            //..........
            next = new ConnectState();
        }
    
        @Override
        public void Operation3(){
            
            //$$$$$$$$$$
            next = new OpenState();
        }
    
    }
    
    public class CloseState extends NetworkState{
    
    
        @Override
        public void Operation1(){
    
            //**********
            next = new ConnectState();
        }
    
        @Override
        public void Operation2(){
    
            //..........
            next = new OpenState();
        }
    
        @Override
        public void Operation3(){
    
            //$$$$$$$$$$
            next = new CloseState();
        }
    
    }
    
    public class ConnectState extends NetworkState{ }
    
    public class WaitingState extends NetworkState{ }
    //...
    
    
    class NetworkProcessor{
        
        NetworkState state;
    
    
    
        public NetworkProcessor(NetworkState state){
            
            this.state = state;
        }

        public void Operation1(){
            //...
            state.Operation1();
            state = state.next;
            //...
        }
    
        public void Operation2(){
            //...
            state.Operation2();
            state = state.next;
            //...
        }
    
        public void Operation3(){
            //...
            state.Operation3();
            state = state.next;
            //...
        }
    
    }

模式总结

优点

缺点

上一篇下一篇

猜你喜欢

热点阅读