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 }
与简单工厂不同的是,在计算乘,除,不需要修改代码,而是直接在外部添加代码
简单工厂:类方法中实例化对象,通过父类进行指向,每一个子类中完成自己独立的运算,根据多态调用正确的方法。
工厂方法:简单工厂中的方法创建实例部分给抽象成各个类的方法,不同的类用来创建不同的实例对象。