C# 窗体工厂类 - 简单工厂模式演示案例

  1. 定义窗体接口和具体窗体类
cs 复制代码
// IForm.cs - 窗体接口
public interface IForm
{
    string Title { get; }
    void Show();
    void Hide();
    string GetFormType();
}

// MainForm.cs - 主窗体
public class MainForm : Form, IForm
{
    private Label label;
    
    public string Title => "主窗体";
    
    public MainForm()
    {
        InitializeComponent();
    }
    
    private void InitializeComponent()
    {
        this.Text = "主窗体";
        this.Size = new Size(400, 300);
        
        label = new Label
        {
            Text = "这是主窗体",
            Font = new Font("微软雅黑", 12),
            Location = new Point(50, 50),
            Size = new Size(200, 30)
        };
        
        this.Controls.Add(label);
    }
    
    public string GetFormType()
    {
        return "MainForm";
    }
}

// SettingsForm.cs - 设置窗体
public class SettingsForm : Form, IForm
{
    private Button closeButton;
    
    public string Title => "设置窗体";
    
    public SettingsForm()
    {
        InitializeComponent();
    }
    
    private void InitializeComponent()
    {
        this.Text = "设置窗体";
        this.Size = new Size(400, 300);
        
        closeButton = new Button
        {
            Text = "关闭",
            Location = new Point(150, 100),
            Size = new Size(100, 30)
        };
        
        closeButton.Click += (sender, e) => this.Hide();
        
        this.Controls.Add(closeButton);
    }
    
    public string GetFormType()
    {
        return "SettingsForm";
    }
}

// ReportForm.cs - 报表窗体
public class ReportForm : Form, IForm
{
    private DataGridView dataGridView;
    
    public string Title => "报表窗体";
    
    public ReportForm()
    {
        InitializeComponent();
        LoadSampleData();
    }
    
    private void InitializeComponent()
    {
        this.Text = "报表窗体";
        this.Size = new Size(500, 400);
        
        dataGridView = new DataGridView
        {
            Location = new Point(20, 20),
            Size = new Size(440, 320)
        };
        
        this.Controls.Add(dataGridView);
    }
    
    private void LoadSampleData()
    {
        dataGridView.Columns.Add("ID", "编号");
        dataGridView.Columns.Add("Name", "名称");
        dataGridView.Columns.Add("Value", "数值");
        
        dataGridView.Rows.Add("001", "项目A", "100");
        dataGridView.Rows.Add("002", "项目B", "200");
        dataGridView.Rows.Add("003", "项目C", "300");
    }
    
    public string GetFormType()
    {
        return "ReportForm";
    }
}
  1. 创建窗体工厂类
cs 复制代码
// FormFactory.cs - 窗体工厂类
public static class FormFactory
{
    public enum FormType
    {
        MainForm,
        SettingsForm,
        ReportForm
    }
    
    // 简单的工厂方法
    public static IForm CreateForm(FormType formType)
    {
        switch (formType)
        {
            case FormType.MainForm:
                return new MainForm();
            case FormType.SettingsForm:
                return new SettingsForm();
            case FormType.ReportForm:
                return new ReportForm();
            default:
                throw new ArgumentException($"不支持的表单类型: {formType}");
        }
    }
    
    // 通过字符串创建窗体
    public static IForm CreateForm(string formType)
    {
        if (Enum.TryParse(formType, out FormType type))
        {
            return CreateForm(type);
        }
        else
        {
            throw new ArgumentException($"无效的表单类型: {formType}");
        }
    }
    
    // 带参数的工厂方法
    public static IForm CreateForm(string formType, string title)
    {
        var form = CreateForm(formType);
        
        // 如果窗体是Form类型,设置标题
        if (form is Form winForm)
        {
            winForm.Text = title;
        }
        
        return form;
    }
}
  1. 使用示例程序
cs 复制代码
// Program.cs - 主程序
public class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        
        // 创建主窗体
        var mainForm = new Form
        {
            Text = "窗体工厂演示",
            Size = new Size(600, 500)
        };
        
        // 创建按钮
        var btnMainForm = new Button
        {
            Text = "打开主窗体",
            Location = new Point(50, 50),
            Size = new Size(150, 40)
        };
        
        var btnSettingsForm = new Button
        {
            Text = "打开设置窗体",
            Location = new Point(50, 120),
            Size = new Size(150, 40)
        };
        
        var btnReportForm = new Button
        {
            Text = "打开报表窗体",
            Location = new Point(50, 190),
            Size = new Size(150, 40)
        };
        
        var btnDynamicForm = new Button
        {
            Text = "动态创建窗体",
            Location = new Point(50, 260),
            Size = new Size(150, 40)
        };
        
        // 显示信息标签
        var lblInfo = new Label
        {
            Location = new Point(250, 50),
            Size = new Size(300, 200),
            Font = new Font("微软雅黑", 10)
        };
        
        // 按钮点击事件
        btnMainForm.Click += (sender, e) =>
        {
            var form = FormFactory.CreateForm(FormFactory.FormType.MainForm);
            form.Show();
            lblInfo.Text = $"已创建: {form.GetFormType()}\n标题: {form.Title}";
        };
        
        btnSettingsForm.Click += (sender, e) =>
        {
            var form = FormFactory.CreateForm(FormFactory.FormType.SettingsForm);
            form.Show();
            lblInfo.Text = $"已创建: {form.GetFormType()}\n标题: {form.Title}";
        };
        
        btnReportForm.Click += (sender, e) =>
        {
            var form = FormFactory.CreateForm(FormFactory.FormType.ReportForm);
            form.Show();
            lblInfo.Text = $"已创建: {form.GetFormType()}\n标题: {form.Title}";
        };
        
        btnDynamicForm.Click += (sender, e) =>
        {
            // 通过字符串创建窗体
            var form = FormFactory.CreateForm("ReportForm", "自定义报表");
            form.Show();
            lblInfo.Text = $"已创建: {form.GetFormType()}\n标题: {(form as Form)?.Text}";
        };
        
        // 添加控件到主窗体
        mainForm.Controls.AddRange(new Control[] 
        { 
            btnMainForm, 
            btnSettingsForm, 
            btnReportForm,
            btnDynamicForm,
            lblInfo 
        });
        
        // 运行程序
        Application.Run(mainForm);
    }
}
  1. 扩展:使用配置文件创建窗体
cs 复制代码
// 配置文件读取示例
public static class ConfigurableFormFactory
{
    public static IForm CreateFormFromConfig(string formKey)
    {
        // 从配置文件读取窗体类型
        var config = new Dictionary<string, string>
        {
            { "Home", "MainForm" },
            { "UserSettings", "SettingsForm" },
            { "DataReport", "ReportForm" }
        };
        
        if (config.TryGetValue(formKey, out string formType))
        {
            return FormFactory.CreateForm(formType);
        }
        else
        {
            throw new KeyNotFoundException($"配置中未找到窗体键: {formKey}");
        }
    }
}
  1. 简单工厂模式的优势

  2. 封装性:将对象的创建逻辑封装在工厂类中

  3. 可扩展性:添加新窗体类型时,只需修改工厂类

  4. 解耦:客户端代码不依赖具体窗体类

  5. 统一管理:所有窗体创建通过同一入口

6.客户端代码示例

cs 复制代码
public class Client
{
    public void UseFormFactory()
    {
        // 方式1:使用枚举
        IForm form1 = FormFactory.CreateForm(FormFactory.FormType.MainForm);
        
        // 方式2:使用字符串
        IForm form2 = FormFactory.CreateForm("SettingsForm");
        
        // 方式3:带参数创建
        IForm form3 = FormFactory.CreateForm("ReportForm", "月度报表");
        
        // 显示窗体
        form1.Show();
        form2.Show();
        form3.Show();
        
        Console.WriteLine($"创建了窗体: {form1.GetFormType()}");
    }
}

7.总结

这个示例演示了如何使用简单工厂模式创建不同类型的窗体,客户端代码不需要知道具体窗体的创建细节,只需通过工厂类统一接口创建所需窗体。

相关推荐
V搜xhliang02466 小时前
3D 点云处理(PCL)
人工智能·目标检测·计算机视觉·3d·分类·知识图谱
金山几座6 小时前
C#学习记录-类(Class)
开发语言·学习·c#
The Shio9 小时前
OptiByte:一个可视化协议设计与多语言代码生成工具
网络·物联网·c#·.net·业界资讯
我是唐青枫10 小时前
C#.NET Pipelines 深入解析:高性能 IO 管道与零拷贝协议处理实战
c#·.net
蓝天星空10 小时前
跨平台开发语言对比
开发语言·c#·.net
阿蒙Amon10 小时前
C#常用类库-详解JetBrains.Annotations
前端·数据库·c#
向哆哆10 小时前
交通标识与信号灯数据集(1000张图片已划分、已标注)AI训练适用于目标检测任务
人工智能·目标检测·计算机视觉
jghhh0111 小时前
运动图像的运动轨迹检测与特征点跟踪MATLAB实现
人工智能·计算机视觉·matlab
老鱼说AI12 小时前
《深入理解计算机系统》(CSAPP)2.2:整数数据类型与底层机器级表示
开发语言·汇编·算法·c#
Daydream.V12 小时前
Opencv高端操作——上采样/下采样及拉普拉斯金字塔
人工智能·opencv·计算机视觉