返回

反射 + 抽象工厂模式切换不同的实现方法

发布时间:2022-10-02 16:50:02 249
# git

概述

工厂模式(Abstract Factory)定义 :提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

实现

1、在项目中,创建接口IA

  •  
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;
namespace 工厂{ public interface IA { string RequestId(); }}

2、实现方法1

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;
namespace 工厂{ public class a1 : IA { public string RequestId(){ return "a11111"; } }}

3、实现方法2

  •  
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;
namespace 工厂{ public class a2 : IA { public string RequestId() { return "a22222"; } }}

测试

使用反射的方式,切换不同的实现方法

  •  
  •  
  public IActionResult Index()  {        var a1 = (工厂.IA)Assembly.Load("工厂").CreateInstance("工厂.a1");        Console.WriteLine(a1);        var a2 = (工厂.IA)Assembly.Load("工厂").CreateInstance("工厂.a2");        Console.WriteLine(a2);        return View();  }

结果如下,达到预期效果

代码地址:

​​https://gitee.com/conanOpenSource_admin/Example/tree/master/%E5%B7%A5%E5%8E%82​​

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
开箱即用的前端图片压缩方案 2022-10-02 16:15:19