C# 设计模式,工厂方法
生活随笔
收集整理的這篇文章主要介紹了
C# 设计模式,工厂方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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與簡(jiǎn)單工廠不同的是,在計(jì)算乘,除,不需要修改代碼,而是直接在外部添加代碼
簡(jiǎn)單工廠:類方法中實(shí)例化對(duì)象,通過(guò)父類進(jìn)行指向,每一個(gè)子類中完成自己獨(dú)立的運(yùn)算,根據(jù)多態(tài)調(diào)用正確的方法。
工廠方法:簡(jiǎn)單工廠中的方法創(chuàng)建實(shí)例部分給抽象成各個(gè)類的方法,不同的類用來(lái)創(chuàng)建不同的實(shí)例對(duì)象。
轉(zhuǎn)載于:https://www.cnblogs.com/zgrh/p/11115140.html
總結(jié)
以上是生活随笔為你收集整理的C# 设计模式,工厂方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: TCP握手为什么需要三次通信
- 下一篇: 打印 PRINT