dimanche 11 décembre 2022

Where to put static fields used in builder pattern?

Using a builder pattern I want to have static fields used in all instances. Do I put them in the Url class or in the UrlBuilder class as static fields or do I extract them into a new class to only hold the static fields?

The expected result is the ability to create a Url instance by using the Builder class and a switch case logic in the UrlBuilder constructor.

Here is a code example:

public class Url {

  //required parameters
  private String homePage;
  private String boardSuffix;

  public String getHomePage() {
    return homePage;
  }

  public String getBoardSuffix() {
    return boardSuffix;
  }

  private Url(UrlBuilder builder) {
    this.homePage = builder.homePage;
    this.boardSuffix = builder.boardSuffix;
  }

  //Builder class
  public static class UrlBuilder {

    //required parameters
    private String homePage;
    private String boardSuffix;

    public UrlBuilder(String homePage, String boardSuffix) {
      this.homePage = homePage;
      this.boardSuffix = boardSuffix;
    }

    public Url build() {
      return new Url(this);
    }

  }

}

I've tried placing the static fields in a "Constants" enum, but got lost in the reflection of enums, while trying to prepare tests.

Aucun commentaire:

Enregistrer un commentaire