Home > Software design >  Hide third party class's java.util.date behind adapter pattern? (wrapper)
Hide third party class's java.util.date behind adapter pattern? (wrapper)

Time:11-15

Is this considered adapter pattern? Is this a valid use case? Is it a good implementation?

// 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();
  }

}

I'm just trying to hide the old java.util.Date API and use the new LocalDate instead in my code.

CodePudding user response:

As wiki says:

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.

yeah, this is Adapter pattern in action. Why? As you adapted your method getCreateDate to return LocalDate type.

  • Related