java - 在适配器模式后面隐藏第三方类的 java.util.date 吗? (包装)

标签 java oop design-patterns adapter

这被认为是适配器模式吗?这是一个有效的用例吗?这是一个好的实现吗?

// 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/

相关文章:

java - 从 JDeveloper 11.1.2.4 迁移我的应用程序后,JDeveloper 12c 出现错误

php - 数据映射器,仅用于CRUD操作?

javascript - mordernizr 中这是什么 javascript 模式?

cocoa - cocoa 应用程序中有多少个典型的 Controller 类?

java - 无工厂策略模式中开关应该放在哪里?

java - 为现有类动态添加注解

java - 如何在J2ME中无需单击按钮即可激活功能键?

java - 从 json 响应调用时 GSON 抛出错误

php - 我如何在 PHP 中声明 'sub-objects'

java - java和php之间的细微差别