简单工厂模式

示例场景:饮料工厂

假设我们有一个饮料工厂,可以生产咖啡和茶两种饮料。我们希望使用工厂模式来管理对象的创建。

代码实现

cs 复制代码
using System;

namespace SimpleFactoryPattern
{
    // 抽象产品:饮料
    public abstract class Beverage
    {
        public abstract void Prepare();
    }

    // 具体产品:咖啡
    public class Coffee : Beverage
    {
        public override void Prepare()
        {
            Console.WriteLine("Preparing a cup of coffee.");
        }
    }

    // 具体产品:茶
    public class Tea : Beverage
    {
        public override void Prepare()
        {
            Console.WriteLine("Preparing a cup of tea.");
        }
    }

    // 工厂类
    public class BeverageFactory
    {
        public static Beverage CreateBeverage(string type)
        {
            return type.ToLower() switch
            {
                "coffee" => new Coffee(),
                "tea" => new Tea(),
                _ => throw new ArgumentException("Invalid beverage type.")
            };
        }
    }

    // 客户端代码
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the type of beverage (coffee/tea):");
            string type = Console.ReadLine();

            try
            {
                // 使用工厂创建对象
                Beverage beverage = BeverageFactory.CreateBeverage(type);
                beverage.Prepare();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

代码说明

  1. 抽象产品 (Beverage)

    • 提供一个基类或接口,定义所有具体产品的通用行为。
  2. 具体产品 (Coffee, Tea)

    • 实现 Beverage 抽象类,并提供具体产品的行为。
  3. 工厂类 (BeverageFactory)

    • 包含一个静态方法 CreateBeverage,根据传入的参数决定创建哪种类型的对象。
  4. 客户端代码 (Main)

    • 客户端无需知道具体产品的创建逻辑,只需要调用工厂方法,并使用返回的对象。

工厂模式的优点

  1. 解耦:客户端与具体产品的创建逻辑解耦,提升代码的可维护性。
  2. 灵活性:易于扩展新产品类型,只需修改工厂类即可。

注意事项

简单工厂模式虽然简单易用,但如果需要支持大量产品类型,可能会导致工厂类过于复杂,此时可以考虑使用工厂方法模式抽象工厂模式来优化设计。

相关推荐
玩泥巴的6 小时前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21888 小时前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理10 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi10 小时前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo12311 小时前
matlab画图工具
开发语言·matlab
dustcell.11 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame11 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone11 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549612 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月12 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js