• C#设计模式系列:简单工厂模式(Simple Factory)


    出自:http://www.cnblogs.com/libingql/p/3887577.html

    1. 简单工厂模式简介

    1.1 定义

      简单工厂模式定义一个Factory类,可以根据参数的不同返回不同类的实例,被创建的实例通常有共同的父类。

      简单工厂模式只需要一个Factory类。

      简单工厂模式又称为静态工厂模式,Factory类为静态类或包含静态方法。

    1.2 使用频率

       中

    2. 简单工厂模式结构

    2.1 结构图

    2.2 参与者

      简单工厂模式参与者:

      ◊ Product:抽象产品类,将具体产品类公共的代码进行抽象和提取后封装在一个抽象产品类中。

      ◊ ConcreteProduct:具体产品类,将需要创建的各种不同产品对象的相关代码封装到具体产品类中。

      ◊ Factory:工厂类,提供一个工厂类用于创建各种产品,在工厂类中提供一个创建产品的工厂方法,该方法可以根据所传入参数的不同创建不同的具体产品对象。

      ◊ Client:客户端类,只需调用工厂类的工厂方法并传入相应的参数即可得到一个产品对象。

    3. 简单工厂模式结构实现

    3.1 Product类抽象实现

      Product.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public abstract class Product
        {
        }
    }
    复制代码

      ConcreteProduct.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public class ConcreteProduct : Product
        {
        }
    }
    复制代码

      Factory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public class Factory
        {
            /// <summary>
            /// 静态方法创建Product实例
            /// </summary>
            public static Product CreateProduct()
            {
                return new ConcreteProduct();
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.Structural;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Product product = Factory.CreateProduct();
                Console.WriteLine("Created {0}", product.GetType().Name);
            }
        }
    }
    复制代码

      运行结果:

    Created ConcreteProduct
    请按任意键继续. . .

    3.2 Product接口类实现

      IProduct.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public interface IProduct
        {
            void Display();
        }
    }
    复制代码

      Product.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public class Product : IProduct
        {
            public void Display()
            {
                Console.WriteLine("DesignPatterns.SimpleFactoryPattern.Structural.Product");
            }
        }
    }
    复制代码

      Factory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Reflection;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public class Factory
        {
            /// <summary>
            /// Factory返回IProduct的静态方法
            /// </summary>
            /// <returns></returns>
            public static IProduct Create()
            {
                // 使用new直接创建接口的具体类
                //return new DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product();
    
                // 通过映射创建接口的具体类
                return (IProduct)Assembly.Load("DesignPatterns.SimpleFactoryPattern").CreateInstance("DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product");
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                IProduct product = Factory.Create();
                product.Display();
            }
        }
    }
    复制代码

    4. 简单工厂模式实践应用

    4.1 实践应用——运算操作

      Operation.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 运算类
        /// </summary>
        public abstract class Operation
        {
            public double NumberA { get; set; }
            public double NumberB { get; set; }
    
            public virtual double GetResult()
            {
                const double result = 0;
                return result;
            }
        }
    }
    复制代码

      Plus.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 加法运算
        /// </summary>
        public class Plus : Operation
        {
            public override double GetResult()
            {
                return NumberA + NumberB;
            }
        }
    }
    复制代码

      Minus.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 减法运算
        /// </summary>
        public class Minus : Operation
        {
            public override double GetResult()
            {
                return NumberA - NumberB;
            }
        }
    }
    复制代码

      Multiply.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class Multiply : Operation
        {
            public override double GetResult()
            {
                return NumberA * NumberB;
            }
        }
    }
    复制代码

      Divide.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class Divide :Operation
        {
            public override double GetResult()
            {
                return NumberA / NumberB;
            }
        }
    }
    复制代码

      OperationFactory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class OperationFactory
        {
            public static Operation CreateOperate(string operate)
            {
                Operation operation = null;
    
                switch (operate)
                {
                    case "+":
                        operation = new Plus();
                        break;
                    case "-":
                        operation = new Minus();
                        break;
                    case "*":
                        operation = new Multiply();
                        break;
                    case "/":
                        operation = new Divide();
                        break;
                }
    
                return operation;
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.Practical;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Operation operateion = OperationFactory.CreateOperate("+");
                operateion.NumberA = 10;
                operateion.NumberB = 5;
    
                Console.WriteLine(operateion.GetResult());
            }
        }
    }
    复制代码

    4.2 实践应用——银行支付接口

      IPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public interface IPayment
        {
            bool Payfor(decimal money);
        }
    }
    复制代码

      ABCPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class ABCPayment : IPayment
        {
            public bool Payfor(decimal money)
            {
                // 调用中国农业银行支付接口进行支付
                return true;
            }
        }
    }
    复制代码

      ICBCPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class ICBCPayment : IPayment
        {
            public bool Payfor(decimal money)
            {
                // 调用中国工商银行支付接口进行支付
                return true;
            }
        }
    }
    复制代码

      PaymentFactory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
       public class PaymentFactory
        {
           public static IPayment CreatePayment(string bank)
           {
               IPayment payment = null;
               switch (bank)
               { 
                   case "ABC":
                       payment = new ABCPayment();
                       break;
                   case "ICBC":
                       payment = new ICBCPayment();
                       break;
               }
    
               return payment;
           }
        }
    }
    复制代码

      OrderService.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
       public class OrderService
        {
           public bool CreateOrder(string bank)
           {
               decimal money=100m;
               var payment = PaymentFactory.CreatePayment(bank);
    
               return payment.Payfor(money);
           }
        }
    }
    复制代码

      在OrderService类中,不依赖具体的支付类,只通过PaymentFactory来获取真正的支付类。

    5. 简单工厂模式应用分析

    5.1 简单工厂模式优点

      ◊ 实现了创建和使用分离;

      ◊ Client无需知道所创建的ConcreteProduct类名,只需要知道ConcreteProduct所对应的参数。

    5.2 简单工厂模式缺点

      ◊ Factory类集中了所有ConcreteProduct的创建逻辑,职责过重。一旦需要添加新的ConcreteProduct,则需要修改Factory逻辑。这样违背了OCP(开放-关闭原则)

      ◊ 由于使用了static方法,造成Factory无法形成基于继承的结构。

    1. 简单工厂模式简介

    1.1 定义

      简单工厂模式定义一个Factory类,可以根据参数的不同返回不同类的实例,被创建的实例通常有共同的父类。

      简单工厂模式只需要一个Factory类。

      简单工厂模式又称为静态工厂模式,Factory类为静态类或包含静态方法。

    1.2 使用频率

       中

    2. 简单工厂模式结构

    2.1 结构图

    2.2 参与者

      简单工厂模式参与者:

      ◊ Product:抽象产品类,将具体产品类公共的代码进行抽象和提取后封装在一个抽象产品类中。

      ◊ ConcreteProduct:具体产品类,将需要创建的各种不同产品对象的相关代码封装到具体产品类中。

      ◊ Factory:工厂类,提供一个工厂类用于创建各种产品,在工厂类中提供一个创建产品的工厂方法,该方法可以根据所传入参数的不同创建不同的具体产品对象。

      ◊ Client:客户端类,只需调用工厂类的工厂方法并传入相应的参数即可得到一个产品对象。

    3. 简单工厂模式结构实现

    3.1 Product类抽象实现

      Product.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public abstract class Product
        {
        }
    }
    复制代码

      ConcreteProduct.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public class ConcreteProduct : Product
        {
        }
    }
    复制代码

      Factory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Structural
    {
        public class Factory
        {
            /// <summary>
            /// 静态方法创建Product实例
            /// </summary>
            public static Product CreateProduct()
            {
                return new ConcreteProduct();
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.Structural;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Product product = Factory.CreateProduct();
                Console.WriteLine("Created {0}", product.GetType().Name);
            }
        }
    }
    复制代码

      运行结果:

    Created ConcreteProduct
    请按任意键继续. . .

    3.2 Product接口类实现

      IProduct.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public interface IProduct
        {
            void Display();
        }
    }
    复制代码

      Product.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public class Product : IProduct
        {
            public void Display()
            {
                Console.WriteLine("DesignPatterns.SimpleFactoryPattern.Structural.Product");
            }
        }
    }
    复制代码

      Factory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Reflection;
    
    namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
    {
        public class Factory
        {
            /// <summary>
            /// Factory返回IProduct的静态方法
            /// </summary>
            /// <returns></returns>
            public static IProduct Create()
            {
                // 使用new直接创建接口的具体类
                //return new DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product();
    
                // 通过映射创建接口的具体类
                return (IProduct)Assembly.Load("DesignPatterns.SimpleFactoryPattern").CreateInstance("DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product");
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                IProduct product = Factory.Create();
                product.Display();
            }
        }
    }
    复制代码

    4. 简单工厂模式实践应用

    4.1 实践应用——运算操作

      Operation.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 运算类
        /// </summary>
        public abstract class Operation
        {
            public double NumberA { get; set; }
            public double NumberB { get; set; }
    
            public virtual double GetResult()
            {
                const double result = 0;
                return result;
            }
        }
    }
    复制代码

      Plus.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 加法运算
        /// </summary>
        public class Plus : Operation
        {
            public override double GetResult()
            {
                return NumberA + NumberB;
            }
        }
    }
    复制代码

      Minus.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        /// <summary>
        /// 减法运算
        /// </summary>
        public class Minus : Operation
        {
            public override double GetResult()
            {
                return NumberA - NumberB;
            }
        }
    }
    复制代码

      Multiply.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class Multiply : Operation
        {
            public override double GetResult()
            {
                return NumberA * NumberB;
            }
        }
    }
    复制代码

      Divide.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class Divide :Operation
        {
            public override double GetResult()
            {
                return NumberA / NumberB;
            }
        }
    }
    复制代码

      OperationFactory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class OperationFactory
        {
            public static Operation CreateOperate(string operate)
            {
                Operation operation = null;
    
                switch (operate)
                {
                    case "+":
                        operation = new Plus();
                        break;
                    case "-":
                        operation = new Minus();
                        break;
                    case "*":
                        operation = new Multiply();
                        break;
                    case "/":
                        operation = new Divide();
                        break;
                }
    
                return operation;
            }
        }
    }
    复制代码

      Program.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    using DesignPatterns.SimpleFactoryPattern.Practical;
    
    namespace DesignPatterns.SimpleFactoryPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Operation operateion = OperationFactory.CreateOperate("+");
                operateion.NumberA = 10;
                operateion.NumberB = 5;
    
                Console.WriteLine(operateion.GetResult());
            }
        }
    }
    复制代码

    4.2 实践应用——银行支付接口

      IPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public interface IPayment
        {
            bool Payfor(decimal money);
        }
    }
    复制代码

      ABCPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class ABCPayment : IPayment
        {
            public bool Payfor(decimal money)
            {
                // 调用中国农业银行支付接口进行支付
                return true;
            }
        }
    }
    复制代码

      ICBCPayment.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
        public class ICBCPayment : IPayment
        {
            public bool Payfor(decimal money)
            {
                // 调用中国工商银行支付接口进行支付
                return true;
            }
        }
    }
    复制代码

      PaymentFactory.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
       public class PaymentFactory
        {
           public static IPayment CreatePayment(string bank)
           {
               IPayment payment = null;
               switch (bank)
               { 
                   case "ABC":
                       payment = new ABCPayment();
                       break;
                   case "ICBC":
                       payment = new ICBCPayment();
                       break;
               }
    
               return payment;
           }
        }
    }
    复制代码

      OrderService.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DesignPatterns.SimpleFactoryPattern.Practical
    {
       public class OrderService
        {
           public bool CreateOrder(string bank)
           {
               decimal money=100m;
               var payment = PaymentFactory.CreatePayment(bank);
    
               return payment.Payfor(money);
           }
        }
    }
    复制代码

      在OrderService类中,不依赖具体的支付类,只通过PaymentFactory来获取真正的支付类。

    5. 简单工厂模式应用分析

    5.1 简单工厂模式优点

      ◊ 实现了创建和使用分离;

      ◊ Client无需知道所创建的ConcreteProduct类名,只需要知道ConcreteProduct所对应的参数。

    5.2 简单工厂模式缺点

      ◊ Factory类集中了所有ConcreteProduct的创建逻辑,职责过重。一旦需要添加新的ConcreteProduct,则需要修改Factory逻辑。这样违背了OCP(开放-关闭原则)

      ◊ 由于使用了static方法,造成Factory无法形成基于继承的结构。

  • 相关阅读:
    C#窗体操作的小技巧
    C#操作Xml
    Path类对路径字符串的操作
    Google Maps 基础
    C#时间操作总结
    根据地理坐标计算瓦片行列号
    使用VBA宏批量修改表格
    检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法
    Asp.net实现URL重写
    VS2013利用ajax访问不了json文件——VS2013配置webconfig识别json文件
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/6513149.html
Copyright © 2020-2023  润新知