簡單工廠模式UML圖 |
class simpleFactory { public static Operation CreateOperate(string oper) { Operation opera = null; switch (oper) { case "+": opera = new Add(); break; case "-": opera = new Sub(); break; case "*": opera = new Mul(); break; case "/": opera = new Div(); break; } return opera; } }
class Operation { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } }
class Add:Operation { public override double GetResult() { double r = NumberA + NumberB; return r; } }
非UML圖,講解下面程式碼用 |
public partial class MainWindow : Window
{
Operation oper = new Operation(); //Operation型別的oper一開始參考Operation物件。
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//tb_opera, tb_numbera, tb_numberb, tb_result為TextBox控制項
//變數oper依輸入的運算式,而改變參考對象,此圖示參考到Add物件,而一開始參考的Operation物件會取消。
oper = simpleFactory.CreateOperate(tb_opera.Text);
oper.NumberA = double.Parse(tb_numbera.Text);
oper.NumberB = double.Parse(tb_numberb.Text);
//變數oper呼叫參考到的Add物件裡的GetResult()函式。
tb_result.Text = oper.GetResult().ToString();
}
}
簡單工廠模式讓使用者端需要參考兩個類別 Operation與simpleFactory,因此耦合度還可以改善.
範例程式碼
參考大話設計一書
沒有留言:
張貼留言