lvweizhu的專欄
阿新 • • 發佈:2018-12-20
就是在設計好的類基礎之上再增加一個工廠類,來對已經寫好的類進行排程管理,在使用時,通過這個工廠類進行相應例項化。
例子:
定義一個類:
public 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()//virtual關鍵字用於指定屬性或方法在派生類中重寫 { double result = 0; return result; } }
寫兩個子類繼承:OperationSub類
class OperationSub:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
OperationAdd類:
class OperationAdd:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
構造工廠:
class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; default:break; } return oper; } }
進行使用:
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.ReadLine();
設計模式的所有內容都參考自程傑的大話設計模式,特此說明。