1.簡單工廠模式
阿新 • • 發佈:2018-11-02
文章目錄
原理
這種型別的設計模式屬於建立型模式,它提供了一種建立物件的最佳方式。
在工廠模式中,我們在建立物件時不會對客戶端暴露建立邏輯,並且是通過使用一個共同的介面來指向新建立的物件。
意圖
定義一個建立物件的介面,讓其子類自己決定例項化哪一個工廠類,工廠模式使其建立過程延遲到子類進行。
主要解決
主要解決介面選擇的問題。
程式碼
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 簡單工廠模式 { class Program { static void Main(string[] args) { Operation oper; oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); Console.Write("result: " + result); Console.ReadKey(); } } }
Operation.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 簡單工廠模式 { //簡單工廠類 class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } } //運算類 class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get { return _numberA; } set { _numberA = value; } } public double NumberB { get { return _numberB; } set { _numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } //加法類 class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } //減法類 class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } //乘法類 class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } //除法類 class OperationDiv : Operation { public override double GetResult() { double result = 0; if (NumberB == 0) { throw new Exception("除數不能為0."); } result = NumberA / NumberB; return result; } } }
參考
參考書籍:《大話設計模式》
參考連結: 菜鳥教程.