1、工廠模式
factory從若干個可能類創建對象。
例如:如果創建一個通信類接口,並有多種實現方式,可以使用factory創建一個實現該接口的對象,factory可以根據我們的選擇,來創建適合的對象。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace Demo { public interface ICommunication { bool Send(object data); } public class Serial:ICommunication { public bool Send(object data) { Console.WriteLine("通過串口發送一個數據"); return true; } } public class Lan:ICommunication { public bool Send(object data) { Console.WriteLine("通過網口發送一個數據"); return true; } } public class CommunicationFactory { public ICommunication CreateCommunicationFactory(string style) { switch(style) { case "Serial": return new Serial(); case "Lan": return new Lan(); } return null; } } class Program { static void Main(string[] args) { CommunicationFactory factory = new CommunicationFactory(); Console.WriteLine("請輸入通信類型:Lan、Serial"); string input = Console.ReadLine(); object data = new object(); factory.CreateCommunicationFactory(input).Send(data); Console.ReadKey(); } } }
運行結果: