小山

付出最大努力,追求最高成就,享受最佳生活,收获无悔人生

博客园 首页 新随笔 联系 订阅 管理

 

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()); 
        }
 
    }
 
}
 
posted on 2005-10-30 18:15  小山  阅读(1032)  评论(2编辑  收藏  举报