編程時一門技術,更是一門藝術
簡單工廠模式利用面向對象方式通過繼承、封裝、多態把程序的耦合度降低,設計模式使得程序更加靈活,容易修改,易於復用。
下面是服務器計算器代碼:
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignModel
{
/// <summary>
/// 計算器
/// </summary>
public class Calculator //創建一個計算器的基類可以接受兩個參數,任何算法只需重寫計算結果方法即可。
{
private double _numberA;
private double _numberB;
public double NumberA
{
get { return this._numberA; }
set { this._numberA = value; }
}
public double NumberB
{
get { return this._numberB; }
set { this._numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
/// <summary>
/// 加法
/// </summary>
public class Add : Calculator //每添加一種計算方式只需添加一個計算類並重寫基類方法即可
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
/// <summary>
/// 減法
/// </summary>
public class Sub : Calculator
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
/// <summary>
/// 計算器工廠
/// </summary>
public class CalculatorFactory
{
public static Calculator GetResult(string oper)
{
Calculator calcu = null;
switch (oper)
{
case "+":
calcu = new Add();
break;
case "-":
calcu = new Sub();
break;
}
return calcu;
}
}
}
復制代碼 代碼如下:
static void Main(string[] args)
{
Console.WriteLine("請輸入數字A:");
string numbera = Console.ReadLine();
Console.WriteLine("請輸入運算符:");
string oper = Console.ReadLine();
Console.WriteLine("請輸入數字B:");
string numberb = Console.ReadLine();
Calculator c = CalculatorFactory.GetResult(oper);
c.NumberA = Convert.ToDouble(numbera);
c.NumberB = Convert.ToDouble(numberb);
Console.WriteLine(string.Format("{0}{1}{2}={3}", numbera, oper, numberb, c.GetResult()));
Console.ReadLine();
}
基本驗證沒加,學習練習的同學可以自己加上
28種設計模式後續更新
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignModel
{
/// <summary>
/// 計算器
/// </summary>
public class Calculator //創建一個計算器的基類可以接受兩個參數,任何算法只需重寫計算結果方法即可。
{
private double _numberA;
private double _numberB;
public double NumberA
{
get { return this._numberA; }
set { this._numberA = value; }
}
public double NumberB
{
get { return this._numberB; }
set { this._numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
/// <summary>
/// 加法
/// </summary>
public class Add : Calculator //每添加一種計算方式只需添加一個計算類並重寫基類方法即可
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
/// <summary>
/// 減法
/// </summary>
public class Sub : Calculator
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
/// <summary>
/// 計算器工廠
/// </summary>
public class CalculatorFactory
{
public static Calculator GetResult(string oper)
{
Calculator calcu = null;
switch (oper)
{
case "+":
calcu = new Add();
break;
case "-":
calcu = new Sub();
break;
}
return calcu;
}
}
}
本文就是.net設計模式中的簡單工廠模式的內容了,非常簡單,下一篇,我們來談談策略模式