您的位置:首页 > 编程语言 > C#

C#简单工厂设计模式实现计算器

2017-07-12 01:37 801 查看

一、首先创建PlusOperation类库,其中包含抽象父类Operation,以及加、减、乘、除四个子类!

(1)父类Operation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NameSpaceOperation
{
public abstract class Operation
{
public int NumberOne { get; set; }
public int NubmerTwo { get; set; }
public Operation(int a,int b)
{
this.NumberOne = a;
this.NubmerTwo = b;

}
public abstract int GetResult();
}
}


(2)加法子类Add

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NameSpaceOperation
{
public class Add : Operation
{
public Add(int a, int b) : base(a, b)
{
}

public override int GetResult()
{
return this.NumberOne + this.NubmerTwo;
}
}
}


(3)减法子类Sub

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NameSpaceOperation
{
public class Sub : Operation
{
public Sub(int a, int b) : base(a, b)
{
}

public override int GetResult()
{
return this.NumberOne - this.NubmerTwo;
}
}
}


(4)乘法子类Mul

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NameSpaceOperation
{
public class Mul : Operation
{
public Mul(int a, int b) : base(a, b)
{
}

public override int GetResult()
{
return this.NumberOne * this.NubmerTwo;
}
}
}


(5)除法子类Div

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NameSpaceOperation
{
public class Div : Operation
{
public Div(int a, int b) : base(a, b)
{
}

public override int GetResult()
{
return this.NumberOne / this.NubmerTwo;
}
}
}


二、创建项目SimpleFactoryPatternCalculator,引入PlusOperation类库,添加NameSpaceOperation命名空间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NameSpaceOperation;

namespace SimpleFactoryPatternCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入你的第一个数字");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入你的第二个数字");
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入你的运算符");
string strOper = Console.ReadLine();
Operation oper = GetOperation(strOper,a, b);
if (oper!=null)
{
int result = oper.GetResult();
Console.WriteLine("{0}{1}{2}={3}",a,strOper,b,result);
}
else
{
Console.WriteLine("没有你需要的运算符");
}

}
static Operation GetOperation(string oper,int a,int b)
{
Ope
4000
ration operation = null;
switch (oper)
{
case "+":
operation = new Add(a, b);
break;
case "-":
operation = new Sub(a, b);
break;
case "*":
operation = new Mul(a, b);
break;
case "/":
operation = new Div(a, b);
break;
}
return operation;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式 c#