zoukankan      html  css  js  c++  java
  • 23、Interpreter 解释器模式

    1Interpreter

    使使使

    (Interpreter Pattern)使

    使

    2

    1使

    AbstractNodeDirectionNodeActionNodeDistanceNodeAndNodeSentenceNode

     import java.util.*;  
     
     //  
     abstract class AbstractNode {  
        public abstract String interpret();  
     }  
     
     //And  
     class AndNode extends AbstractNode {  
        private AbstractNode left; //And  
        private AbstractNode right; //And  
     
        public AndNode(AbstractNode left, AbstractNode right) {  
            this.left = left;  
            this.right = right;  
        }  
     
        //And  
        public String interpret() {  
            return left.interpret() + "" + right.interpret();  
        }  
     }  
     
     //   
    class SentenceNode extends AbstractNode {   
       private AbstractNode direction;   
       private AbstractNode action;   
       private AbstractNode distance;    

       public SentenceNode(AbstractNode direction,AbstractNode action,AbstractNode distance) {   
           this.direction = direction;   
           this.action = action;   
           this.distance = distance;   
       }    

       //   
       public String interpret() {   
           return direction.interpret() + action.interpret() + distance.interpret();   
       }     
    }    

    //   
    class DirectionNode extends AbstractNode {   
       private String direction;    

       public DirectionNode(String direction) {   
           this.direction = direction;   
       }    

       //   
       public String interpret() {   
           if (direction.equalsIgnoreCase("up")) {   
               return "";   
           }   
           else if (direction.equalsIgnoreCase("down")) {   
               return "";   
           }   
           else if (direction.equalsIgnoreCase("left")) {   
               return "";   
           }   
           else if (direction.equalsIgnoreCase("right")) {   
               return "";   
           }   
           else {   
               return "";   
           }   
       }   
    }    

    //   
    class ActionNode extends AbstractNode {   
       private String action;    

       public ActionNode(String action) {   
           this.action = action;   
       }    

       //   
       public String interpret() {   
           if (action.equalsIgnoreCase("move")) {   
               return "";   
           }   
           else if (action.equalsIgnoreCase("run")) {   
               return "";   
           }   
           else {   
               return "";   
           }   
       }   
    }    

    //   
    class DistanceNode extends AbstractNode {   
       private String distance;    

       public DistanceNode(String distance) {   
           this.distance = distance;   
       }    

    //   
       public String interpret() {   
           return this.distance;   
       }     
    }    

    //   
    class InstructionHandler {   
       private String instruction;   
       private AbstractNode node;    

       public void handle(String instruction) {   
           AbstractNode left = null, right = null;   
           AbstractNode direction = null, action = null, distance = null;   
           Stack stack = new Stack(); //   
           String[] words = instruction.split(" "); //   
           for (int i = 0; i < words.length; i++) {   
    //andSentenceNodeandandand                  if (words[i].equalsIgnoreCase("and")) {   
                   left = (AbstractNode)stack.pop(); //   
                   String word1= words[++i];   
                   direction = new DirectionNode(word1);   
                   String word2 = words[++i];   
                   action = new ActionNode(word2);   
                   String word3 = words[++i];   
                   distance = new DistanceNode(word3);   
                   right = new SentenceNode(direction,action,distance); //   
                   stack.push(new AndNode(left,right)); //   
               }   
               //SentenceNode   
               else {   
                   String word1 = words[i];   
                   direction = new DirectionNode(word1);   
                   String word2 = words[++i];   
                   action = new ActionNode(word2);   
                   String word3 = words[++i];   
                   distance = new DistanceNode(word3);   
                   left = new SentenceNode(direction,action,distance);   
                   stack.push(left); //   
               }   
           }   
           this.node = (AbstractNode)stack.pop(); //   
       }    

       public String output() {   
           String result = node.interpret(); //   
           return result;   
       }   
    }

    InstructionHandler123andand123andAnd

     class Client {  
        public static void main(String args[]) {  
            String instruction = "up move 5 and down run 10 and left move 5";  
            InstructionHandler handler = new InstructionHandler();  
            handler.handle(instruction);  
            String outString;  
            outString = handler.output();  
            System.out.println(outString);  
        }  
     }

     5105

    2

    LOOP 2 PRINT SPACE SPACE PRINT BREAK END PRINT SPACE SPACE PRINT

          
          
          

    ContextNodeExpressionNodeCommandNodeLoopCommandNodePrimitiveCommandNode

     import java.util.*;  
     
     //(Action Token)  
     class Context {  
        private StringTokenizer tokenizer; //StringTokenizer(Token)  
        private String currentToken; //  
     
        public Context(String text) {  
            tokenizer = new StringTokenizer(text); //StringTokenizer  
            nextToken();  
        }  
     
        //  
        public String nextToken() {  
            if (tokenizer.hasMoreTokens()) {  
                currentToken = tokenizer.nextToken();   
           }   
           else {   
               currentToken = null;   
           }   
           return currentToken;   
       }    

       //   
       public String currentToken() {   
           return currentToken;   
       }    

       //   
       public void skipToken(String token) {   
           if (!token.equals(currentToken)) {   
               System.err.println("" + currentToken + "");   
               }   
           nextToken();   
       }    

       //   
       public int currentNumber() {   
           int number = 0;   
           try{   
               number = Integer.parseInt(currentToken); //   
           }   
           catch(NumberFormatException e) {   
               System.err.println("" + e);   
           }   
           return number;   
       }   
    }    

    //   
    abstract class Node {   
       public abstract void interpret(Context text); //   
       public abstract void execute(); //   
    }    

    //   
    class ExpressionNode extends Node {   
       private ArrayList<Node> list = new ArrayList<Node>(); //    

       public void interpret(Context context) {   
           //Context   
           while (true){   
               //退   
               if (context.currentToken() == null) {   
                   break;   
               }   
               //ENDEND   
               else if (context.currentToken().equals("END")) {   
                   context.skipToken("END");   
                   break;   
               }   
               //   
               else {   
                   Node commandNode = new CommandNode();   
                   commandNode.interpret(context);   
                   list.add(commandNode);   
               }   
           }   
       }    

       //   
       public void execute() {   
           Iterator iterator = list.iterator();   
           while (iterator.hasNext()){   
               ((Node)iterator.next()).execute();   
           }   
       }   
    }    

    //   
    class CommandNode extends Node {   
       private Node node;    

       public void interpret(Context context) {   
           //LOOP   
           if (context.currentToken().equals("LOOP")) {   
               node = new LoopCommandNode();   
               node.interpret(context);   
           }   
           //   
           else {   
               node = new PrimitiveCommandNode();   
               node.interpret(context);   
           }   
       }    

       public void execute() {   
           node.execute();   
       }   
    }    

    //   
    class LoopCommandNode extends Node {   
       private int number; //   
       private Node commandNode; //    

       //   
       public void interpret(Context context) {   
           context.skipToken("LOOP");   
           number = context.currentNumber();   
           context.nextToken();   
           commandNode = new ExpressionNode(); //   
           commandNode.interpret(context);   
       }    

       public void execute() {   
           for (int i=0;i<number;i++)   
               commandNode.execute();   
       }   
    }    

    //   
    class PrimitiveCommandNode extends Node {   
       private String name;   
       private String text;    

       //   
       public void interpret(Context context) {   
           name = context.currentToken();   
           context.skipToken(name);   
           if (!name.equals("PRINT") && !name.equals("BREAK") && !name.equals ("SPACE")){   
               System.err.println("");   
           }   
           if (name.equals("PRINT")){   
               text = context.currentToken();   
               context.nextToken();   
           }   
       }    

       public void execute(){   
           if (name.equals("PRINT"))   
               System.out.print(text);   
           else if (name.equals("SPACE"))   
               System.out.print(" ");   
           else if (name.equals("BREAK"))   
               System.out.println();   
       }   
    }

    ContextnextToken()currentToken()skipToken()(Token)

     class Client{  
        public static void main(String[] args){  
            String text = "LOOP 2 PRINT  SPACE SPACE PRINT  BREAK END PRINT  SPACE SPACE PRINT ";  
            Context context = new Context(text);  
     
            Node node = new ExpressionNode();  
            node.interpret(context);  
            node.execute();  
        }  
     }

          
          
          

    LOOP 2 LOOP 2 PRINT SPACE SPACE PRINT BREAK END PRINT SPACE SPACE PRINT BREAK END

    3Interpreter

    AbstractExpression

    TerminalExpression

    NonterminalExpression

    Context

    4

    使XML广使EclipseEclipse ASTJava

    123

    1234

    使 123

    公众号发哥讲

    这是一个稍偏基础和偏技术的公众号,甚至其中包括一些可能阅读量很低的包含代码的技术文,不知道你是不是喜欢,期待你的关注。

    img

    如果你觉得文章还不错,就请点击右上角选择发送给朋友或者转发到朋友圈~

    ● 扫码关注我们

    据说看到好文章不推荐的人,服务器容易宕机!

     

     

  • 相关阅读:
    Silverlight 2 应用程序部署到任意HTML页面
    推荐一个工具包自定义HTTP 404错误
    WPF/Silverlight的UI和逻辑完全分离
    ObservableCollection 类
    Silverlight + ModelViewViewModel (MVVM)
    IIS7 request routing 和load balancing module发布
    DeepEarth:使用Silverlight的地图控件
    在Vista安装SQL 2008 Express遭遇属性不匹配错误解决办法
    RIA 应用程序模式
    WinForm界面开发之酒店管理系统报表篇
  • 原文地址:https://www.cnblogs.com/naimao/p/13446559.html
Copyright © 2011-2022 走看看