这被认为是适配器模式吗?这是一个有效的用例吗?这是一个好的实现吗?
// 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。
最佳答案
如wiki说:
the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface.1 It is often used to make existing classes work with others without modifying their source code.
是的,这就是适配器模式的实际应用。为什么?当您调整方法 getCreateDate
以返回 LocalDate
类型时。
应该考虑一件事,两个类应该共享一些抽象,例如抽象类或接口(interface)。必须是可以互换的。让我举个例子。
我们需要一些抽象,例如接口(interface):
public interface IProduct
{
public LocalDate getCreateDate();
public int getId();
}
和产品
类:
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()));
关于java - 在适配器模式后面隐藏第三方类的 java.util.date 吗? (包装),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74430191/