using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;ide
namespace 購物_工廠模式_ { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //3.開始寫事件了 private void button1_Click(object sender, EventArgs e) { try { double t1 = Convert.ToDouble(textBox1.Text); double t2 = Convert.ToDouble(textBox2.Text); label7.Text = (t1 * t2).ToString(); } catch { MessageBox.Show("請輸入數量或單價"); } MyClass mc = GongChang.Createclass(comboBox1.SelectedItem.ToString()); label4.Text = mc.at(Convert.ToDouble(label7.Text)).ToString(); } } //2.建一個工廠類: //用這個類 調用其餘類中的函數 public class GongChang { public static MyClass Createclass(string c) { switch (c) { case "正常收費": return new MyClass1(); case "打8折": return new MyClass2(0.8); case "滿300送50": return new MyClass3(300, 50); default: return null; } } } //1.首先三種付款方式的類 //建立個抽象類,使用抽象方法傳入沒有付款方式時的價錢 //以後重寫抽象方法,更改價錢(三種付款方式) public abstract class MyClass { public abstract double at(double money); } //三種方式: //正常收費 public class MyClass1 : MyClass { public override double at(double money) { return money; } } //打折 public class MyClass2 : MyClass { private double dazhe = 1; public MyClass2(double dze) { dazhe = dze; } public override double at(double money) { return money * dazhe; } } //滿300免50 public class MyClass3 : MyClass { private double x = 0; private double y = 0; public MyClass3(double _x, double _y) { x = _x; y = _y; } public override double at(double money) { if (money > x) { return money - Math.Floor(money / x) * y;//300的倍數*50 } else return money; } } }