适配器设计模式是一种结构设计模式 ,可以帮助我们连接到通过不同接口公开相似功能的旧版或第三方代码。
适配器的现实世界是我们用来将USB电缆连接到以太网端口的类比。
在设计面向对象的应用程序时,当我们的客户希望使用特定类型的对象并且我们有一个第三方API提供相同的功能但通过不兼容的接口时,我们可能会感到需要适配器。
它也被称为包装器,因为它通过一个新接口包装现有代码,使其与客户端兼容。
术语:
让我们知道在谈论适配器模式时使用的术语:
- 客户端:要使用第三方库或外部系统的类
- Adaptee:我们要使用的第三方库或外部系统中的类
- 目标接口:客户端将使用的所需接口
- 适配器:此类位于客户端和适配器之间,并实现目标接口
使用适配器模式:
假设我们有一个ShopInventory ,其中维护着一个产品列表。 后来,我们接管了另一家出售杂货的商店库存。 现在,我们要将这些项目添加到ShopInventory中 。 我们这里存在的问题是,尽管GroceryItem只是一种产品,但与Product接口无关。
为了解决这个问题,我们将使用适配器模式。 我们将创建一个GroceryItemAdapter ,它将实现Product接口:
借助适配器,我们现在可以将GroceryItem视为产品,而无需更改第三方代码( GroceryItem )中的任何内容。
Java实现:
首先定义一个Product和一个ShopInventory类:
- public interface Product {
-
- String getName();
- double getPrice();
- }
-
- public class ShopInventory {
-
- private List<Product> products;
-
- public ShopInventory() {
- this.products = new ArrayList<>();
- }
-
- public void addProduct(Product product) {
- this.products.add(product);
- }
-
- public void removeProduct(Product product) {
- this.products.remove(product);
- }
- }
我们刚刚接管的第三方商店拥有GroceryItem :
- //third-party code
- public class GroceryItem {
-
- String itemName;
- int costPerUnit;
-
- //constructor, getters and setters
- }
由于我们的ShopInventory只保存Product类型的项目,因此我们为新引入的GroceryItem创建一个适配器:
- public class GroceryItemAdapter implements Product {
-
- private GroceryItem groceryItem;
-
- public GroceryItemAdapter(GroceryItem groceryItem) {
- this.groceryItem = groceryItem;
- }
-
- public String getName() {
- return groceryItem.getItemName();
- }
-
- public double getPrice() {
- return groceryItem.getCostPerUnit();
- }
- }
这样,我们现在可以将我们的常规产品和杂货添加到我们的ShopInventory中:
- //code in our main method
- ShopInventory inventory = new ShopInventory();
-
- //adding regular store products - ones that implement Product interface
- inventory.addProduct(new CosmeticProduct("Lavie Handbag", 5000.0));
- inventory.addProduct(new FitnessProduct("Yoga SmartFit", 2000.75));
-
-
- //adding GroceryItem to the store using an adapter
- GroceryItem groceryItem = new GroceryItem("Wheat Flour", 100);
- inventory.addProduct(new GroceryItemAdapter(groceryItem));
结论:
适配器模式可帮助我们连接两个不兼容的接口,以显示相同的业务功能。
使用适配器模式,我们将现有接口转换为客户端代码期望的另一个接口。
翻译自: https://www.javacodegeeks.com/2019/08/adapter-design-pattern-in-java.html