【设计模式】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. 灵活性:可以通过配置文件、数据库、甚至网络请求来决定加载哪个工厂。

相关推荐
xcLeigh4 小时前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
花落人散处4 小时前
CDiskClean 开发历程——文件&进程实时监控-实现方案参考
c#
猿长大人8 小时前
C# | MediatR 入门指南:后端架构解耦
分布式·后端·架构·c#·.net
回忆2012初秋8 小时前
C# 中的 EAP:基于事件的异步编程全面指南(一)
开发语言·c#
曹牧9 小时前
C#:Type
开发语言·c#
用户37215742613510 小时前
C# 如何在 Excel 中创建下拉列表:3 种常见数据源实现方式
c#
czhc114007566310 小时前
工业视觉检测中的通用设计模式与技术笔记
c#
明如正午11 小时前
【C#】volatile 关键字深度解析:为什么我的停止按钮有时失灵?
c#
猿长大人1 天前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json