适配器设计模式有什么需求

适配器设计模式有什么需求

本文介绍了适配器设计模式有什么需求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的适配器设计模式示例代码中,为什么引入新类而不在客户端中使用多个接口?

In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?

 code>可以使用该API,而无需更改其代码。

Sometimes you have a given API that you can't change (legacy/external-library/etc...) and you want to make your classes be able to work with that API without changing their code.

假设您使用的API具有 ISomethingToSerialize

Lets say you use an API which has an ISomethingToSerialize

public interface ISomethingToSerialize
{
    object[] GetItemsToSerialize();
}

该API也具有序列化函数:

public class SerializationServices
{
    byte[] Serialize(ISomethingToSerialize objectToSerialize);
}

现在您拥有类在您的代码中,您不想或无法更改它,我们将其称为 MyUnchangeableClass 。

Now you have a class in your code, and you don't want or not able to change it, let's call it MyUnchangeableClass.

此类没有实现 ISomethingToSerialize ,但是您想使用 API对其进行序列化,因此您创建 AdapterClass ,该实现实现 ISomethingToSerialize 以允许 MyUnchangeableClass 即可使用它,而无需单独实现:

This class doesn't implement ISomethingToSerialize but you want to serialize it using the API so you create AdapterClass which implement ISomethingToSerialize to allow MyUnchangeableClass to use it without implementing it by itself:

public class AdapterClass : ISomethingToSerialize
{
    public AdapterClass(MyUnchangeableClass instance)
    {
        mInstance = instance;
    }

    MyUnchangeableClass mInstance;

    public object[] GetItemsToSerialize()
    {
        return mInstance.SomeSpecificGetter();
    }
}

现在您可以使用

MyUnchangeableClass instance = ... //Constructor or factory or something...
AdapterClass adapter = new AdapterClass(instance)
SerializationServices.Serialize(adapter);

序列化 MyUnchangeableClass 的实例它本身不满足API的要求。

to serialize an instance of MyUnchangeableClass even though it doesn't meet the requirements of the API by itself.

这篇关于适配器设计模式有什么需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:03