概述
工厂模式( )定义:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
抽象工厂模式( )是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式抽象工厂模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
实现
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();
}
结果如下抽象工厂模式,达到预期效果
代码地址:
%E5%B7%A5%E5%8E%82
限时特惠:本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情
站长微信:Jiucxh
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。