摘要:(200-07-02) C#.NET 抽象類別 工廠模式
抽象類別(父) 上課程式 csmod03.rar
using System; using System.Collections.Generic; using System.Linq; using System.Text; //抽象類別-具有一個功能只有規格 無法實做 namespace csmod03 { public abstract class Pump { //Data Field private String _name; //建構子 public Pump() { } public Pump(String _name) { this._name = _name; } //功能(抽象描述 沒有實作{} public abstract void doIt(); } }
子類別1(子)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csmod03 { public class OilPump:Pump { public override void doIt() { System.Console.WriteLine("送油馬達"); } } }
子類別2(子)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csmod03 { //繼承抽象類別 public class WaterPump:Pump { //實做method public override void doIt() { System.Console.WriteLine("揚水馬達!!"); } } }
子類別3(子)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csmod03 { public class ThrowWaterPump:WaterPump { //Overriding 覆寫父親既定method public override void doIt() { System.Console.WriteLine("抽水馬達!!"); } } }
工廠( Factory )
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csmod03 { public class Factory { //提供一個共用功能(類別多型化) public static Pump getPump(PumpType type) { //父類別變數 Pump pump = null; switch (type) { case PumpType.DrawWater: pump = new ThrowWaterPump(); break; case PumpType.OliWater: pump = new OilPump(); break; case PumpType.Water: pump = new WaterPump(); break; } return pump; } } //列舉清單 public enum PumpType { Water, DrawWater, OliWater } }
主程式
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csmod03 { class TestPumpAbstract { //主程式 public static void Main() { //要物件 //父類別 子類別建構物件 Pump pump=Factory.getPump(PumpType.Water); pump.doIt(); //掃描列舉項目 String[] items = Enum.GetNames(typeof(PumpType)); foreach(String s in items) { System.Console.WriteLine(s); } } } }