设计模式学习之简单工厂模式

本文详细解析了简单工厂模式的概念及其在C#编程中的实现方式,通过一个具体的例子展示了如何通过传入运算符号来实例化并调用相应的操作类,实现了基本的加法运算,并阐述了如何通过此模式扩展更多运算方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先上一张UML类图。


再看看代码:

Operation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Operation
    {
        private double numberA = 0;
        private double numberB = 0;

        public double NumberA
        {
            set;
            get;
        }
        public double NumberB
        {
            set;
            get;
        }

        public virtual double GetResult()
        {
            return 0;
        }

    }
}

Add.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Add:Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = base.NumberA + base.NumberB;
            return result;
            //return base.GetResult();
        }
    }
}
OperationFactory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class OperationFactory
    {
        public static Operation CreateOperation(string operation)
        {
            Operation o = null;
            switch (operation)
            {
                case "+": o = new Add(); break;
                default: o = new Add(); break;
            }
            return o;
        }
    }
}
使用它:

Operation operation = OperationFactory.CreateOperation("+");
operation.NumberA = 10;
operation.NumberB = 100;
Console.WriteLine(operation.GetResult());
Console.ReadLine();
回过头,来看看这个设计模式:

简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。它是工厂模式家族中最简单实用的模式。它其实就是根据传入工厂类的参数来决定要创建哪一种的产品实例。上面的代码就是通过传入一个运算符号,实例化出一个合适的对象,通过多态,返回父类的方式实现了计算结果。

如果要增加一种运算方法,可以这么做:1.增加一个类,该类继承Operation。2.在OperationFactory里面修改switch分枝。

这个模式解决对象创建的问题。














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值