Java中的适配器设计模式
適配器設計模式是一種結構設計模式 ,可以幫助我們連接到通過不同接口公開相似功能的舊版或第三方代碼。
適配器的現實世界是我們用來將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
總結
以上是生活随笔為你收集整理的Java中的适配器设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 万有引力定律公式 万有引力定律公式是什么
- 下一篇: 外部集成 网页制作_外部服务的集成测试