适配器设计模式有什么需求? [英] what is the need of Adapter Design pattern?
问题描述
在下面的适配器设计模式示例代码中,为什么引入新类而不在客户端中使用多个接口?
In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
我有以下与上述代码相关的查询。
I have the below queries related to the above code.
- 如果ShoppingPortalClient直接继承VendorAdaptee,会怎样?
- 在哪种情况下我们需要适配器类? / li>
- 为什么不是简单继承所需类,而是创建此模式来访问另一个类方法?
推荐答案
有时候,您有一个无法更改的给定API(旧版/外部库/等),并且您想创建您的类 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.
这篇关于适配器设计模式有什么需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!