分享

解释器模式(Robot pattern)

 漂在北方的狼 2007-03-28
namespace DesignPattern.Interpreter 

    
public abstract class Expression 
    

        
public abstract bool Interpret(); 
    }
 
 
    
public class Constant : Expression 
    

        
private bool m_val; 
 
        
public Constant(bool val) 
        

            
this.m_val=val; 
        }
 
 
        
public override bool Interpret() 
        

            
return this.m_val; 
        }
 
 
        
public override string ToString() 
        

            
return this.m_val.ToString(); 
        }
 
    }
 
 
    
public class And : Expression 
    

        
public Expression left,right; 
         
        
public And(Expression left,Expression right) 
        

            
this.left=left; 
            
this.right=right; 
        }
 
 
        
public override bool Interpret() 
        

            
return left.Interpret()&&right.Interpret(); 
        }
 
 
        
public override string ToString() 
        

            
return "("+this.left.ToString()+" && "+this.right.ToString()+")"
        }
 
    }
 
 
    
public class Or : Expression 
    

        
public Expression left,right; 
         
        
public Or(Expression left,Expression right) 
        

            
this.left=left; 
            
this.right=right; 
        }
 
 
        
public override bool Interpret() 
        

            
return left.Interpret()||right.Interpret(); 
        }
 
 
        
public override string ToString() 
        

            
return "("+this.left.ToString()+" || "+this.right.ToString()+")"
        }
 
    }
 
 
    
public class Not : Expression 
    

        
private Expression exp; 
 
        
public Not(Expression exp) 
        

            
this.exp=exp; 
        }
 
 
        
public override bool Interpret() 
        

            
return !exp.Interpret(); 
        }
 
 
        
public override string ToString() 
        

            
return "(! "+exp.ToString()+")"
        }
 
    }
 
 
    
public class Client 
    

        
public static void Main() 
        

            Expression exp
=new Or(new And(new Constant(true),new Constant(false)), 
            
new And(new Constant(true),new Not(new Constant(false)))); 
            Console.WriteLine(exp.ToString()
+"="+exp.Interpret()); 
        }
 
    }
 
}
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多