/// <summary>
/// 6.创建工厂方法模式(抽象工厂:接口)
/// </summary>
interface IFactory //父接口(父类工厂)
{
/// <summary>
/// 此父接口提供一个无参的函数方法
/// </summary>
/// <returns></returns>
Operation CreateOperation();
}
/// <summary>
/// 定义子类工厂,并继承父类工厂(父接口)
/// </summary>
class FactoryAdd : IFactory
{
/// <summary>
/// 封装与父类工厂同名函数(返回值类型亦相同)
/// </summary>
/// <returns></returns>
public Operation CreateOperation()
{
//返回上面OperationAdd子类
return new OperationAdd();
}
}
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace FactoryModel 8 { 9 //====================使用C#,利用简单工厂模式,实现简单的计算器功能==================== 10 //考察时知识点:面向对象三大特性——继承、封装、多态 11 /// <summary> 12 /// 1.定义父类,同时也是一个封装 13 /// </summary> 14 class Operation 15 { 16 //2.因为要让子类能够对父类进行访问,故应要将参数定义为受保护的变量类型 17 protected int numberA; 18 protected int numberB; 19 //定义属性(必写) 20 public int NumberA 21 { 22 get { return numberA; } 23 set { numberA = value; } 24 } 25 public int NumberB 26 { 27 get { return numberB; } 28 set { numberB = value; } 29 } 30 //3.封装虚方法,以供子类进行重写 31 public virtual int getResule() 32 { 33 int result = 0; 34 return result; 35 } 36 } 37 /// <summary> 38 /// 4.定义子类,继承父类,并对父类进行重写(加法) 39 /// </summary> 40 class OperationAdd : Operation 41 { 42 public override int getResule() 43 { 44 return numberA + numberB; 45 } 46 } 47 /// <summary> 48 /// 5.定义子类,继承父类,并对父类进行重写(减法) 49 /// </summary> 50 class OperationSub : Operation 51 { 52 public override int getResule() 53 { 54 return numberA - numberB; 55 } 56 } 57 /// <summary> 58 /// 6.创建工厂方法模式(抽象工厂:接口) 59 /// </summary> 60 interface IFactory //父接口(父类工厂) 61 { 62 /// <summary> 63 /// 此父接口提供一个无参的函数方法 64 /// </summary> 65 /// <returns></returns> 66 Operation CreateOperation(); 67 } 68 /// <summary> 69 /// 定义子类工厂,并继承父类工厂(父接口) 70 /// </summary> 71 class FactoryAdd : IFactory 72 { 73 /// <summary> 74 /// 封装与父类工厂同名函数(返回值类型亦相同) 75 /// </summary> 76 /// <returns></returns> 77 public Operation CreateOperation() 78 { 79 //返回上面OperationAdd子类 80 return new OperationAdd(); 81 } 82 } 83 /// <summary> 84 /// 定义子类工厂,并继承父类工厂(父接口) 85 /// </summary> 86 class FactorySub : IFactory 87 { 88 /// <summary> 89 /// 封装与父类工厂同名函数(返回值类型亦相同) 90 /// </summary> 91 /// <returns></returns> 92 public Operation CreateOperation() 93 { 94 ////返回上面OperationAdd子类 95 return new OperationSub(); 96 } 97 } 98 //7.主函数中进行调用 99 class Program 100 { 101 static void Main(string[] args) 102 { 103 //进行加法运算,指定相应的工厂类型即可,无须再次输入运算类型 104 IFactory i = new FactorySub(); 105 //进行减法运算 106 //IFactory ii = new FactorySub(); 107 Operation op = i.CreateOperation(); 108 op.NumberA = 10; 109 op.NumberB = 30; 110 //调用子类中的方法来获取结果 111 int result = op.getResule(); 112 Console.WriteLine(result); 113 Console.ReadKey(); 114 } 115 //如果在后续的编程中仍需要有其他的运算,则只需要在子类中加上相应的子类, 116 //并在工厂方法中中加上相应的工厂类即可即可,无须需改代码,这也就是工厂方法(抽象工厂)的“利”所在 117 } 118 }