這被認為是配接器模式嗎?這是一個有效的用例嗎?這是一個好的實施嗎?
// cannot change this class
public class ProductExample {
private Date createDate;
private Integer id;
public Date getCreateDate() {
return createDate;
}
public Integer getId() {
return id;
}
}
public class ProductExampleAdapter {
private final ProductExample productExample;
public ProductExampleAdapter(ProductExample productExample) {
this.productExample = productExample;
}
public LocalDate getCreateDate() {
return productExample.getCreateDate().toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public Integer getId() {
return productExample.getId();
}
}
我只是想隱藏舊的 java.util.Date API 并在我的代碼中使用新的 LocalDate。
uj5u.com熱心網友回復:
正如維基所說:
配接器模式是一種軟體設計模式(也稱為包裝器,與裝飾器模式共享的替代命名),它允許將現有類的介面用作另一個介面。1它通常用于使現有類與其他類一起作業,而無需修改它們的源代碼。
是的,這就是實際的配接器模式。為什么?當您調整方法getCreateDate以回傳LocalDate型別時。
應該考慮的一件事是,這兩個類應該共享一些抽象,如抽象類或介面。必須可以互換。讓我舉個例子。
我們需要一些抽象,比如介面:
public interface IProduct
{
public LocalDate getCreateDate();
public int getId();
}
和Product類:
public class Product : IProduct
{
public LocalDate getCreateDate()
{
throw new NotImplementedException();
}
public int getId()
{
throw new NotImplementedException();
}
}
和:
public class ProductExampleAdapter : IProduct // "implements" in Java
{
private final ProductExample productExample;
public ProductExampleAdapter(ProductExample productExample) {
this.productExample = productExample;
}
public LocalDate getCreateDate() {
return productExample.getCreateDate().toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public Integer getId() {
return productExample.getId();
}
}
public class ProductExample {
}
然后它可以像這樣使用:
List<IProduct> products = new List<IProduct>();
products.Add(new Product());
products.Add(new ProductExampleAdapter(new ProductExample()));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534249.html
標籤:爪哇哎呀设计模式适配器
上一篇:專案資源管理從學會向上管理開始
