Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Two design approaches to consider</p> <p>The <a href="http://www.hillside.net/plop/plop98/final_submissions/P10.pdf" rel="noreferrer">essence</a> pattern</p> <p>The <a href="http://java.dzone.com/news/factories-builders-and-fluent-" rel="noreferrer">fluent interface</a> pattern</p> <p>These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.</p> <p>An example of the fluent interface in action would be:</p> <pre><code>public class CustomerBuilder { String surname; String firstName; String ssn; public static CustomerBuilder customer() { return new CustomerBuilder(); } public CustomerBuilder withSurname(String surname) { this.surname = surname; return this; } public CustomerBuilder withFirstName(String firstName) { this.firstName = firstName; return this; } public CustomerBuilder withSsn(String ssn) { this.ssn = ssn; return this; } // client doesn't get to instantiate Customer directly public Customer build() { return new Customer(this); } } public class Customer { private final String firstName; private final String surname; private final String ssn; Customer(CustomerBuilder builder) { if (builder.firstName == null) throw new NullPointerException("firstName"); if (builder.surname == null) throw new NullPointerException("surname"); if (builder.ssn == null) throw new NullPointerException("ssn"); this.firstName = builder.firstName; this.surname = builder.surname; this.ssn = builder.ssn; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } public String getSsn() { return ssn; } } import static com.acme.CustomerBuilder.customer; public class Client { public void doSomething() { Customer customer = customer() .withSurname("Smith") .withFirstName("Fred") .withSsn("123XS1") .build(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload