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

相关推荐
努力也学不会java2 小时前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
LoveXming2 小时前
Chapter5—抽象工厂模式
抽象工厂模式
青草地溪水旁2 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
唐青枫4 小时前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
Magnetic_h12 小时前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
A阳俊yi12 小时前
设计模式——结构型模式
设计模式
未来之窗软件服务13 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther13 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎