c# - 在位于外部库中的类上创建抽象
问题描述
我正在处理的 c# 项目引用驻留在外部类库中的“产品”具体类型。“产品”类不实现任何接口。
我想基于“Product”创建一个“IProduct”接口并使用这个接口代码,所以我可以针对接口而不是实现进行编程。
由于我仍然想继续使用“Product”类型,让我的代码知道“Product”实现“IProduct”的好模式是什么?
由于“产品”驻留在外部库中,因此我无法更改其声明(即 Procut:IProduct)。
该类也没有公共构造函数,所以我想扩展它不是一种选择。
对于这种情况,什么是好的解决方案模式?一个包装?
谢谢你。
解决方案
You'd probably want to use the Adapter pattern.
So you can so something like the below:
public class Product
{
// Your Product Class
}
public class MyProduct : Product, IProduct
{
}
Where the MyProduct
class implements the interface but also has all of the public and protected methods/properties available from the Product
class. This allows you to extend the original class without modification to the Product
class which follows the Open/Close principle.
You can read more about this here: https://exceptionnotfound.net/the-daily-design-pattern-adapter/
推荐阅读
- mongodb - 有没有办法在使用 MongoDb 的一个查询中获取文档和相关的方面?
- multithreading - 如果操作系统管理的同一进程中的两个线程同时访问同一虚拟地址,那么在两个执行单元中会发生什么?
- css - Bootstrap CSS:覆盖断点
- express - Heroku Express /w NextJS 端口
- javascript - 如何在 JavaScript 中使用自定义变量
- xml - 我可以在 XSLT 转换后加载 XML 响应吗
- variables - Elisp 延长变量寿命
- c# - 我的播放器正在穿过墙壁(即使它们是刚体)并且下面的脚本不起作用(C#)
- reporting-services - SSRS - 无法删除或管理已部署的报告
- mysql - 从选项(来自 rds - mysql)创建动态框架,提供带有 where 子句的自定义查询