【设计模式】C#反射实现抽象工厂模式

cs 复制代码
using System;
using System.Reflection;

#region 产品接口
public interface IButton
{
    void Paint();
}

public interface ITextBox
{
    void Render();
}
#endregion

#region Windows 产品族
public class WindowsButton : IButton
{
    public void Paint() => Console.WriteLine("Windows 风格按钮");
}

public class WindowsTextBox : ITextBox
{
    public void Render() => Console.WriteLine("Windows 风格文本框");
}
#endregion

#region Mac 产品族
public class MacButton : IButton
{
    public void Paint() => Console.WriteLine("Mac 风格按钮");
}

public class MacTextBox : ITextBox
{
    public void Render() => Console.WriteLine("Mac 风格文本框");
}
#endregion

#region 抽象工厂
public interface IUIFactory
{
    IButton CreateButton();
    ITextBox CreateTextBox();
}
#endregion

#region 具体工厂
public class WindowsFactory : IUIFactory
{
    public IButton CreateButton() => new WindowsButton();
    public ITextBox CreateTextBox() => new WindowsTextBox();
}

public class MacFactory : IUIFactory
{
    public IButton CreateButton() => new MacButton();
    public ITextBox CreateTextBox() => new MacTextBox();
}
#endregion

#region 工厂加载器(通过反射)
public static class FactoryLoader
{
    public static IUIFactory LoadFactory(string className)
    {
        // 获取当前程序集
        Assembly asm = Assembly.GetExecutingAssembly();
        // 根据类名创建实例
        object obj = asm.CreateInstance(className);
        return obj as IUIFactory ?? throw new ArgumentException("无法加载工厂: " + className);
    }
}
#endregion

#region 客户端
class Program
{
    static void Main()
    {
        // 假设这个值来自配置文件 / 数据库 / 用户输入
        string factoryName = "MacFactory"; // 或 "WindowsFactory"

        IUIFactory factory = FactoryLoader.LoadFactory(factoryName);

        IButton button = factory.CreateButton();
        ITextBox textBox = factory.CreateTextBox();

        button.Paint();
        textBox.Render();
    }
}
#endregion

如果 factoryName = "MacFactory",输出

Mac 风格按钮

Mac 风格文本框

如果 factoryName = "WindowsFactory",输出

Windows 风格按钮

Windows 风格文本框

优点

1. 解耦 :客户端无需硬编码 new WindowsFactory(),而是通过反射加载。

2. 可扩展 :只需新增一个工厂类(比如 LinuxFactory),不用改客户端代码。

3. 灵活性:可以通过配置文件、数据库、甚至网络请求来决定加载哪个工厂。

相关推荐
武藤一雄2 小时前
C# 万字拆解线程间通讯?
后端·微软·c#·.net·.netcore·多线程
lljss20202 小时前
C# 定时器类实现1s定时器更新UI
开发语言·c#
白杨攻城狮3 小时前
C# 关于 barierr 心得
开发语言·c#
1024肥宅3 小时前
JavaScript常用设计模式完整指南
前端·javascript·设计模式
江沉晚呤时3 小时前
延迟加载(Lazy Loading)详解及在 C# 中的应用
java·开发语言·microsoft·c#
专注VB编程开发20年3 小时前
C#用API添另静态路由表
c#·静态路由
我是唐青枫3 小时前
C# Params Collections 详解:比 params T[] 更强大的新语法
c#·.net
Zhen (Evan) Wang3 小时前
从客户端的HTTP 请求到后端 .NET 8 API的整个生命周期 - 处理请求和响应的主要方式
c#·.net
用户298698530144 小时前
如何在 C# 中创建、读取和更新 Excel 文档
后端·c#·excel
特立独行的猫a5 小时前
C++观察者模式设计及实现:玩转设计模式的发布-订阅机制
c++·观察者模式·设计模式