zoukankan      html  css  js  c++  java
  • 设计模式(状态模式)

    状态机的使用在各类项目中使用都比较多,设计模式中的状态模式是将状态机的维护抽象出来,并由需要支持改状态机的对象维护起来。

    本文给出一个简单的例子:

    • State
    public abstract class State {
        protected int type;
        public abstract void handler(int input);
        public abstract void showState();
    }
    • ConcreteState
    public class ConcreteState extends State {
    
        @Override
        public void handler(int input) {
            if(1 == input){
                this.type = 2;
            }else if(2 == input){
                this.type = 1;
            }else{
                this.type = 1;
            }
        }
        
        public void showState(){
            System.out.println(this.type);
        }
    }
    • Context
    public class Context {
        private State state;
        
        public Context(State state){
            this.state = state;
        }
        
        public void handlerState(int input){
            state.handler(input);
        }
        
        public void showState(){
            state.showState();
        }
    }
    • App 测试类
    public class App {
    
        public static void main(String[] args) {
            State state = new ConcreteState();
            Context context = new Context(state);
            context.showState();//输出0
            context.handlerState(1);    
            context.showState();//输出2
            context.handlerState(2);
            context.showState();//输出1
        }
    }
  • 相关阅读:
    fmt命令
    wc命令
    grep命令
    head命令
    C/C++语法知识:typedef struct 用法详解
    邻接表无向图的介绍
    邻接矩阵无向图的介绍
    图的基本概念
    careercup-栈与队列 3.6
    careercup-栈与队列 3.5
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4576452.html
Copyright © 2011-2022 走看看