C# 设计模式,工厂方法
生活随笔
收集整理的這篇文章主要介紹了
C# 设计模式,工厂方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#工廠方法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 工廠方法 { 8 class Program { 9 static void Main(string[] args) { 10 IFacotry i = new FactoryAdd(); 11 Operation op = i.CreateOperation(); 12 op.Number1 = 10; 13 op.Number2 = 20; 14 Console.WriteLine(op.getResult()); 15 Console.ReadKey(); 16 } 17 } 18 class Operation { //父類,封裝 19 protected int number1; 20 protected int number2; 21 22 public int Number1 { 23 get { return number1; } 24 set { number1 = value; } 25 } 26 public int Number2 { 27 get { return number2; } 28 set { number2 = value; } 29 } 30 public virtual int getResult() { 31 int result = 0; 32 return result; 33 } 34 } 35 class OperationAdd : Operation { 36 public override int getResult() { 37 return number1 + number2; 38 } 39 } 40 class OperationSub : Operation { 41 public override int getResult() { 42 return number1 - number2; 43 } 44 } 45 interface IFacotry { 46 Operation CreateOperation(); 47 } 48 class FactoryAdd:IFacotry { 49 public Operation CreateOperation() { 50 return new OperationAdd(); 51 } 52 } 53 class FacotrySub : IFacotry { 54 public Operation CreateOperation() { 55 return new OperationSub(); 56 } 57 } 58 } View Code與簡單工廠不同的是,在計算乘,除,不需要修改代碼,而是直接在外部添加代碼
簡單工廠:類方法中實例化對象,通過父類進行指向,每一個子類中完成自己獨立的運算,根據多態調用正確的方法。
工廠方法:簡單工廠中的方法創建實例部分給抽象成各個類的方法,不同的類用來創建不同的實例對象。
轉載于:https://www.cnblogs.com/zgrh/p/11115140.html
總結
以上是生活随笔為你收集整理的C# 设计模式,工厂方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TCP握手为什么需要三次通信
- 下一篇: 浅谈.Net版(C#)的CMP模式