反射使抽象工厂模式的面向对象更上一层楼(知识点:依赖注入,反射,多态性,操作XML文件等)
namespace test
{
#region 使用反射实现的抽象工厂
internal static class ReflectionFactory
{
private static String _windowType;
private static String _styleType;
static ReflectionFactory()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"f:/test.xml");
XmlNode xmlNode = xmlDoc.ChildNodes[0];
_windowType = xmlNode.ChildNodes[0].ChildNodes[0].Value;
_styleType = xmlNode.ChildNodes[1].ChildNodes[0].Value;
}
public static IWindow MakeWindow()
{
return Assembly.Load("test").CreateInstance("test." + _windowType) as IWindow;
}
public static IStyle MakeStyle()
{
return Assembly.Load("test").CreateInstance("test." + _styleType) as IStyle;
}
}
#endregion
#region 操作接口规范
internal interface IStyle
{
String ShowInfo();
}
internal interface IWindow
{
String ShowInfo();
}
#endregion
#region 页面风格
internal sealed class WindowsStyle : IStyle
{
public String Description { get; private set; }
public WindowsStyle()
{
this.Description = "Windows风格按钮";
}
public String ShowInfo()
{
return this.Description;
}
}
internal sealed class MacStyle : IStyle
{
public String Description { get; private set; }
public MacStyle()
{
this.Description = "Mac风格按钮";
}
public String ShowInfo()
{
return this.Description;
}
}
#endregion
#region 窗口风格
internal sealed class WindowsWindow : IWindow
{
public String Description { get; private set; }
public WindowsWindow()
{
this.Description = "Windows风格窗口";
}
public String ShowInfo()
{
return this.Description;
}
}
internal sealed class MacWindow : IWindow
{
public String Description { get; private set; }
public MacWindow()
{
this.Description = "Mac风格窗口";
}
public String ShowInfo()
{
return this.Description;
}
}
#endregion
#region 工厂接口规范
internal interface IFactory
{
IWindow MakeWindow();
IStyle MakeStyle();
}
#endregion
#region 具体工厂的实现
internal sealed class WindowsFactory : IFactory
{
public IWindow MakeWindow()
{
return new WindowsWindow();
}
public IStyle MakeStyle()
{
return new WindowsStyle();
}
}
internal sealed class MacFactory : IFactory
{
public IWindow MakeWindow()
{
return new MacWindow();
}
public IStyle MakeStyle()
{
return new MacStyle();
}
}
#endregion
}
在主程序中这样去调用它:
#region 通过学习接口与反射再次看看抽象工厂模式
IWindow window = ReflectionFactory.MakeWindow();
Console.WriteLine("创建 " + window.ShowInfo());
IStyle style = ReflectionFactory.MakeStyle();
Console.WriteLine("创建 " + style.ShowInfo());
#endregion
XML配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<config>
<window>MacWindow</window>
<style>MacStyle</style>
</config>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)