简单工厂模式

示例场景:饮料工厂

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

代码实现

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. 灵活性:易于扩展新产品类型,只需修改工厂类即可。

注意事项

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

相关推荐
Albert Edison2 小时前
【Python】学生管理系统
开发语言·数据库·python
宇木灵5 小时前
C语言基础-十、文件操作
c语言·开发语言·学习
云泽8085 小时前
C++ 多态入门:虚函数、重写、虚析构及 override/final 实战指南(附腾讯面试题)
开发语言·c++
yanghuashuiyue6 小时前
lambda+sealed+record
java·开发语言
yzx9910137 小时前
Python数据结构入门指南:从基础到实践
开发语言·数据结构·python
衍生星球7 小时前
【JSP程序设计】Servlet对象 — page对象
java·开发语言·servlet·jsp·jsp程序设计
扶苏瑾7 小时前
线程安全问题的产生原因与解决方案
java·开发语言·jvm
小小小米粒8 小时前
函数式接口 + Lambda = 方法逻辑的 “插拔式解耦”
开发语言·python·算法
风吹乱了我的头发~8 小时前
Day31:2026年2月21日打卡
开发语言·c++·算法
蜜獾云9 小时前
JAVA面试题速记-第1期-java基础
java·开发语言