首页 > 解决方案 > 在位于外部库中的类上创建抽象

问题描述

我正在处理的 c# 项目引用驻留在外部类库中的“产品”具体类型。“产品”类不实现任何接口。

我想基于“Product”创建一个“IProduct”接口并使用这个接口代码,所以我可以针对接口而不是实现进行编程。

由于我仍然想继续使用“Product”类型,让我的代码知道“Product”实现“IProduct”的好模式是什么?

由于“产品”驻留在外部库中,因此我无法更改其声明(即 Procut:IProduct)。

该类也没有公共构造函数,所以我想扩展它不是一种选择。

对于这种情况,什么是好的解决方案模式?一个包装?

谢谢你。

标签: c#

解决方案


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/


推荐阅读