一.簡單工廠模式(UML類圖):設計模式
核心類代碼:框架
public class Calc { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } }
public class Add : Calc { public override double GetResult() { return NumberA + NumberB; } }
public class CalcFactory { public static Calc CalcValue(string operate) { Calc calc = null; switch (operate) { case "+": calc = new Add(); break; case "-": calc = new Sub(); break; case "*": calc = new Mul(); break; case "/": calc = new Div(); break; } return calc; } }
客戶端進行調用:ide
static void Main(string[] args) { Calc calc = CalcFactory.CalcValue("+"); calc.NumberA = 5; calc.NumberB = 9; Console.WriteLine(calc.GetResult()); Console.ReadKey(); }
二.工廠方法模式(UML類圖):測試
工廠方法模式(Factory Method)是一種建立型的設計模式,在該模式中父類決定實例的生成方式。可是不決定它要生成的具體的類,具體的處理是交給子類完成的,這樣將生成實例的框架和負責生成實例的類解耦。this
核心類代碼:spa
public interface IFactory { Calc createCalc(); }
public class AddFactory:IFactory { public Calc createCalc() { return new Add(); } }
客戶端進行進行調用:設計
static void Main(string[] args) { IFactory fact = new AddFactory(); Calc calc= fact.createCalc(); calc.NumberA = 2; calc.NumberB = 2; Console.WriteLine(calc.GetResult()); Console.ReadKey(); }
三.工廠方法模式(一個工廠一個產品): code
從簡單入手,下面經過製做身份證IDCard來了解工廠模式:blog
public abstract class Product { public abstract void Use(); }
public abstract class Factory { public Product create(string name) { Product product = createProduct(name); registerProduct(product); return product; } protected abstract Product createProduct(string name); protected abstract void registerProduct(Product product); }
public class IDCard:Product { string name; public IDCard(string name) { Console.WriteLine("製做卡片:"+name); this.name=name; } public override void Use() { Console.WriteLine(name+"使用卡片"); } public string getName() { return name; } }
public class IDCardFactory:Factory { ArrayList list = new ArrayList(); protected override Product createProduct(string name) { return new IDCard(name); } protected override void registerProduct(Product product) { IDCard card = (IDCard)product; list.Add(card.getName()); } public ArrayList getName() { return list; } }
四.工廠方法模式調用測試:繼承
下面實際調用測試一下:
static void Main(string[] args) { Factory factory = new IDCardFactory(); Product card1 = factory.create("小明"); Product card2 = factory.create("小紅"); Product card3 = factory.create("小剛"); card1.use(); card2.use(); card3.use(); Console.ReadKey(); }
輸出信息: