Creational Patterns

Two Recurring Themes of Creational Patterns

  1. They encapsulate knowledge about which concrete classes the system uses
    • Abstracts the instantiation process
  2. Hide how instances of classes are created and put together
    • Helps make a system independent of how its objects are created, composed, or represented


Builder

Problem

Brief Example

public void demo() {
		License license = new LicenseBuilder()
            .setBirthDate(new Date()),
            .setName("John"),
            .setAddressLine1("123 Square Lane"),
            .setCity("Milford"),
            .setState("Delaware"),
            .setZipCode(19720);
            .setLicenseNumber(1238913312)
            .build();
}

Factory

Problem

Brief Example

public class LicenseFactory {
  private LicenseBuilder builder;

  public LicenseFactory(LicenseBuilder builder) {
    this.builder = builder;
  }

  public License createLicense(String addressLine1, String addressLine2, String city, String state, String zipcode) {
      return builder
              .setAddressLine1(addressLine1)
              .setAddressLine2(addressLine2)
              .setCity(city)
              .setState(state)
              .setZipcode(zipcode)
              .createLicense();
  }
  public License createLicense(String firstName, String lastName, Date birthdate, Long licenseNumber) {
      return builder
              .setFirstName(firstName)
              .setLastName(lastName)
              .setBirthDate(birthdate)
              .setLicenseNumber(licenseNumber)
              .createLicense();
  }
}

Prototype Design Pattern

Problem

Solution

Consequences

Brief Example

public class LicenseBuilder {
    private Date birthDate;
    private String firstName;
    private String lastName;
    private Long licenseNumber;
    private Character driverClass;
    private String addressLine1;
    private String addressLine2;
    private String city;
    private String state;
    private String zipcode;

    public LicenseBuilder(LicenseBuilder licenseBuilderToBeCloned) {
        this.firstName = licenseBuilderToBeCloned.firstName;
        this.lastName = licenseBuilderToBeCloned.lastName;
        this.birthDate = licenseBuilderToBeCloned.birthDate;
        this.licenseNumber = licenseBuilderToBeCloned.licenseNumber;
        this.driverClass = licenseBuilderToBeCloned.driverClass;
        this.addressLine1 = licenseBuilderToBeCloned.addressLine1;
        this.addressLine2 = licenseBuilderToBeCloned.addressLine2;
        this.city = licenseBuilderToBeCloned.city;
        this.state = licenseBuilderToBeCloned.state;
        this.zipcode = licenseBuilderToBeCloned.zipcode;
    }
}

Summary