C#设计模式之简单工厂模式

来源:互联网 发布:淘宝正品鞋店推荐 编辑:程序博客网 时间:2024/06/10 17:23

  大家一听到简单工厂这个名字,都会感到很陌生,不知道他是干什么的 ,其实简单工厂模式是类的创建模式

什么意思呢?就是根据提供给它的数据返回几个可能类中的一个类的实例。


其实简单工厂的主要思想就是:我要什么,就问他要(调用方法返回),而不是自己创建(亲自实例化)。


如果需要的东西变了,就不需要重新创建(更改实例化代码),而是仍然问别人要(没有修改任何代码,还是调用那个方法,你只要修改那个方法就够了。)


简单工厂的优点:工程类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对客户端来说,去除了与具体产品的依赖。



接下来是一段代码:一个简单的小例子。求两个数的和,应用了简单工厂模式。


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 简单工厂{
  //父类    public class Operation    {        private double _numberA = 0;        private double _numberB = 0;        public double NumberA        {            get { return _numberA; }            set { _numberA = value; }        }        public double NumberB        {            get { return _numberB; }
//子类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 
简单工厂


{ public class OperationAdd:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }}
/
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 
简单工厂

{ public class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; } return oper; } }}
//Main方法类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 
简单工厂

{ class Program { static void Main(string[] args) { Operation oper; oper = OperationFactory.createOperate("+");// oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine("结果是:" + result); } }}




1 0
原创粉丝点击