使用简单工厂模式改写“生成+-*/”

本代码用于改写http://www.cnblogs.com/resake/archive/2008/06/23/1228039.html提到的生成+-*/表达式。

using System;
using System.Collections.Generic;

#region 应用程序入口
public class Resake
{
    
public static void Main()
    {
        Expresstion ea 
= ExpresstionFactory.CreateExpresstion('+');
        ea.MakeExpresstion();
        ea.ShowResult();
        
        ea 
= ExpresstionFactory.CreateExpresstion('-');
        ea.MakeExpresstion();
        ea.ShowResult();
        
        Console.ReadLine();
    }

}
#endregion 

#region 实际类
public abstract class Expresstion //基类
{
    
protected Random rnd = new Random();
    
protected int result,num1,num2,input;
    
protected readonly int seed = 20;
    
public abstract void MakeExpresstion();
    
public virtual void ShowResult()
    {
        Console.WriteLine(
"num1: {0}, num2: {1}, result: {2}",num1,num2,result);
    }
}

public class ExpresstionAdd:Expresstion //加法
{
    
public override void MakeExpresstion()
    {
        result 
= rnd.Next(1,seed);
        num1 
= rnd.Next(1,result);
        num2 
= result - num1;        
    }
    
    
public override void ShowResult()
    {
        Console.WriteLine(
"{0} + {1} = ? ({2})",num1,num2,result);
    }
    
}

public class ExpresstionSub:Expresstion //减法
{
    
public override void MakeExpresstion()
    {
        result 
= rnd.Next(1,seed);
        num2 
= rnd.Next(1,result);
        num1 
= result+num2;
    }
    
    
public override void ShowResult()
    {
        Console.WriteLine(
"{0} - {1} = ? ({2})",num1,num2,result);
    }
}
#endregion 

#region  简单工厂
public static class ExpresstionFactory
{
    
public static Expresstion CreateExpresstion(char operat)
    {
        Expresstion exp 
= null;
        
switch(operat)
        {
            
case '+':
                exp 
= new ExpresstionAdd();
                
break;
            
case '-':
                exp 
= new ExpresstionSub();
                
break;
        }
        
return exp;
    }
}
#endregion

posted on 2008-06-23 16:22  resake  阅读(441)  评论(0编辑  收藏  举报