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

概述

工厂模式(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

展开阅读全文

页面更新:2024-04-18

标签:抽象   反射   工厂   模式   方法   接口   定义   对象   效果   方式

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top