当前位置: 首页 > news >正文

C#设计模式之AbstractFactory_抽象工厂_对象创建新模式-学习

 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;namespace AbstractFactoryPattern
{// 抽象产品:按钮接口public interface IButton{void Render();string Click();}// 抽象产品:文本框接口public interface ITextBox{void Render();void SetText(string text);string GetText();}// 具体产品:Windows风格按钮public class WindowsButton : Button, IButton{public WindowsButton(){this.Text = "Windows Button";this.BackColor = Color.LightBlue;this.Size = new Size(150, 40);this.Font = new Font("Segoe UI", 10);}public void Render(){Console.WriteLine("渲染Windows风格按钮");}public string Click(){return "Windows按钮被点击";}}// 具体产品:Mac风格按钮public class MacButton : Button, IButton{public MacButton(){this.Text = "Mac Button";this.BackColor = Color.LightGreen;this.Size = new Size(150, 40);this.Font = new Font("Helvetica", 10);this.FlatStyle = FlatStyle.Flat;}public void Render(){Console.WriteLine("渲染Mac风格按钮");}public string Click(){return "Mac按钮被点击";}}// 具体产品:Linux风格按钮public class LinuxButton : Button, IButton{public LinuxButton(){this.Text = "Linux Button";this.BackColor = Color.LightSalmon;this.Size = new Size(150, 40);this.Font = new Font("Ubuntu", 10);}public void Render(){Console.WriteLine("渲染Linux风格按钮");}public string Click(){return "Linux按钮被点击";}}// 具体产品:Windows风格文本框public class WindowsTextBox : TextBox, ITextBox{public WindowsTextBox(){this.Text = "Windows TextBox";this.Size = new Size(200, 30);this.BackColor = Color.AliceBlue;this.Font = new Font("Segoe UI", 10);}public void Render(){Console.WriteLine("渲染Windows风格文本框");}public void SetText(string text){this.Text = text;}public string GetText(){return this.Text;}}// 具体产品:Mac风格文本框public class MacTextBox : TextBox, ITextBox{public MacTextBox(){this.Text = "Mac TextBox";this.Size = new Size(200, 30);this.BackColor = Color.Honeydew;this.Font = new Font("Helvetica", 10);this.BorderStyle = BorderStyle.FixedSingle;}public void Render(){Console.WriteLine("渲染Mac风格文本框");}public void SetText(string text){this.Text = text;}public string GetText(){return this.Text;}}// 具体产品:Linux风格文本框public class LinuxTextBox : TextBox, ITextBox{public LinuxTextBox(){this.Text = "Linux TextBox";this.Size = new Size(200, 30);this.BackColor = Color.MistyRose;this.Font = new Font("Ubuntu", 10);}public void Render(){Console.WriteLine("渲染Linux风格文本框");}public void SetText(string text){this.Text = text;}public string GetText(){return this.Text;}}// 抽象工厂接口public interface IUIFactory{IButton CreateButton();ITextBox CreateTextBox();string GetOSStyle();}// 具体工厂:Windows UI工厂public class WindowsUIFactory : IUIFactory{public IButton CreateButton(){return new WindowsButton();}public ITextBox CreateTextBox(){return new WindowsTextBox();}public string GetOSStyle(){return "Windows风格";}}// 具体工厂:Mac UI工厂public class MacUIFactory : IUIFactory{public IButton CreateButton(){return new MacButton();}public ITextBox CreateTextBox(){return new MacTextBox();}public string GetOSStyle(){return "Mac风格";}}// 具体工厂:Linux UI工厂public class LinuxUIFactory : IUIFactory{public IButton CreateButton(){return new LinuxButton();}public ITextBox CreateTextBox(){return new LinuxTextBox();}public string GetOSStyle(){return "Linux风格";}}// 客户端代码public class UIApplication{private IUIFactory _factory;private IButton _button;private ITextBox _textBox;public UIApplication(IUIFactory factory){_factory = factory;CreateUI();}private void CreateUI(){_button = _factory.CreateButton();_textBox = _factory.CreateTextBox();Console.WriteLine($"创建{_factory.GetOSStyle()}界面元素");_button.Render();_textBox.Render();}public string SimulateUserInteraction(){_textBox.SetText("用户输入文本");return $"{_button.Click()} -> 文本框内容: '{_textBox.GetText()}'";}public Control[] GetUIElements(){return new Control[] { (Control)_button, (Control)_textBox };}}// 演示窗体public class AbstractFactoryDemoForm : Form{private ComboBox _styleComboBox;private Button _applyButton;private Panel _uiPanel;private Label _resultLabel;private UIApplication _currentApp;public AbstractFactoryDemoForm(){this.Text = "抽象工厂模式演示";this.Size = new Size(600, 400);this.StartPosition = FormStartPosition.CenterScreen;InitializeComponents();}private void InitializeComponents(){// 样式选择_styleComboBox = new ComboBox{Location = new Point(20, 20),Size = new Size(150, 30),DropDownStyle = ComboBoxStyle.DropDownList};_styleComboBox.Items.AddRange(new object[] { "Windows", "Mac", "Linux" });_styleComboBox.SelectedIndex = 0;// 应用按钮_applyButton = new Button{Text = "应用风格",Location = new Point(190, 20),Size = new Size(100, 30),BackColor = Color.LightGray};_applyButton.Click += ApplyButton_Click;// 结果标签_resultLabel = new Label{Location = new Point(20, 300),Size = new Size(550, 40),BorderStyle = BorderStyle.FixedSingle};// UI面板_uiPanel = new Panel{Location = new Point(20, 70),Size = new Size(550, 200),BorderStyle = BorderStyle.FixedSingle,BackColor = Color.WhiteSmoke};this.Controls.Add(_styleComboBox);this.Controls.Add(_applyButton);this.Controls.Add(_uiPanel);this.Controls.Add(_resultLabel);// 初始创建ApplyStyle();}private void ApplyButton_Click(object sender, EventArgs e){ApplyStyle();}private void ApplyStyle(){_uiPanel.Controls.Clear();IUIFactory factory = null;switch (_styleComboBox.SelectedItem.ToString()){case "Windows":factory = new WindowsUIFactory();break;case "Mac":factory = new MacUIFactory();break;case "Linux":factory = new LinuxUIFactory();break;}if (factory != null){_currentApp = new UIApplication(factory);var controls = _currentApp.GetUIElements();controls[0].Location = new Point(50, 30);controls[1].Location = new Point(50, 100);_uiPanel.Controls.Add(controls[0]);_uiPanel.Controls.Add(controls[1]);// 添加按钮点击事件((Button)controls[0]).Click += (s, e) => {_resultLabel.Text = _currentApp.SimulateUserInteraction();};_resultLabel.Text = $"已创建{factory.GetOSStyle()}界面";}}}public class A3_AbstractFactory_抽象工厂_对象创建新模式{public static void RunDemo(){Application.EnableVisualStyles();Application.Run(new AbstractFactoryDemoForm());}}
}

抽象工厂模式核心概念

模式结构

  1. 抽象产品 (Abstract Product)

    • 定义产品对象的接口(如 IButtonITextBox

    • 客户端代码通过抽象产品接口操作对象

  2. 具体产品 (Concrete Product)

    • 实现抽象产品接口的具体类(如 WindowsButtonMacTextBox

    • 属于特定产品族的实现

  3. 抽象工厂 (Abstract Factory)

    • 声明创建抽象产品对象的接口(IUIFactory

    • 包含一组创建不同产品的方法

  4. 具体工厂 (Concrete Factory)

    • 实现抽象工厂接口(如 WindowsUIFactory

    • 创建属于特定产品族的具体产品

模式优点

  1. 产品一致性:确保创建的产品属于同一产品族(如所有Windows风格组件)

  2. 解耦客户端与具体类:客户端只与抽象接口交互

  3. 易于切换产品族:只需更改具体工厂即可切换整个产品系列

  4. 符合开闭原则:添加新产品族时无需修改现有代码

学习要点

  1. 产品族概念:一组相关或相互依赖的产品(如Windows风格按钮+文本框)

  2. 平台独立性:客户端代码不依赖于具体平台实现

  3. 创建过程封装:产品创建细节被封装在具体工厂中

  4. 可扩展性:添加新产品族容易(如添加Android风格)

使用场景

  1. 系统需要独立于产品的创建、组合和表示

  2. 系统需要配置多个产品系列中的一个

  3. 需要确保相关产品对象一起使用

  4. 需要提供产品类库,只暴露接口不暴露实现

模式对比

模式特点
抽象工厂模式创建多个产品族,强调产品系列一致性
工厂方法模式创建单一产品,通过子类决定实例化
简单工厂模式创建单一产品,集中决策逻辑

相关文章:

  • 使用 socat 和 xinetd 将程序绑定到端口运行
  • 安卓9.0系统修改定制化____默认开启 开发者选项中的OEM锁解锁选项 开搞篇 五
  • Milvus/ES 插入方案对比
  • OD 算法题 B卷【最多团队】
  • SeaTunnel与Hive集成
  • Mkdocs 阅读时间统计插件
  • 华为云Flexus+DeepSeek征文 | 基于华为云ModelArts Studio搭建PandaWiki知识库问答系统
  • 极客时间《后端存储实战课》阅读笔记
  • linux 阻塞和非阻塞
  • 【一天一个知识点】RAG 是“问答脑”,智能体是“有行动力的大脑”
  • XP POWER EJ ET EY FJ FR 系列软件和驱动程序和手侧
  • 『uniapp』onThemeChange监听主题样式,动态主题不正确生效,样式被覆盖的坑
  • 如何提高电脑打字速度?
  • PHP Swoft2 框架精华系列:Controller 控制器组件解析,用法详解
  • leetcode 1432. 改变一个整数能得到的最大差值 中等
  • PCB设计教程【大师篇】stm32开发板PCB布线(电源部分)
  • 基于C_PSO与BP神经网络回归模型的特征选择方法研究(Python实现)
  • Nginx超快速入门
  • Vite:下一代前端构建工具的革命性突破
  • 对于数据库触发器自动执行的理解
  • 合肥建设网站查询/手机系统流畅神器
  • 施工企业承揽业务不良行为/优化大师怎么卸载
  • wordpress 公众号 会员/长沙seo运营
  • 永济市网站建设/html网页制作软件有哪些
  • 网站建设公司起名/阿里云域名查询和注册
  • 便宜建站空间/网站推广技巧有哪些