The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Strategy Design Pattern

Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

Intent: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it." [GoF]

Open in the interactive referenceDownload the PDF reference

Intent

The intent of the Strategy design pattern is to:
"Define a family of algorithms, encapsulate each one, and make them interchange­able. Strategy lets the algorithm vary independently from clients that use it." [GoF]
See Problem and Solution sections for a more structured description of the intent. [BGI]

  • The Strategy design pattern solves problems like:
    • How can a class be configured with an algorithm at run-time
      instead of implementing an algorithm directly?
    • How can an algorithm be selected and exchanged at run-time?
  • The term algorithm is usually defined as a procedure that takes some value as input, performs a finite number of steps, and produces some value as output.
    From a more general point of view, an algorithm is an arbitrary piece of code that does something appropriate.
  • For example, calculating prices in an order processing system.
    To calculate prices in different ways (depending on run-time conditions like type of customer, volume of sales, product quantity, etc.), it should be possible to select the right pricing algorithm (pricing 'strategy') at run-time.
  • The Strategy pattern describes how to solve such problems:
    • Define a family of algorithms, encapsulate each one, - define separate classes (Strategy1,Strategy2,…) that implement (encapsulate) each algorithm,
    • and make them interchangeable - and define a common interface (Strategy) through which algorithms can be (inter)changed at run-time.

Background Information

  • The Intent section is "A short statement that answers the following questions: What does the design pattern do? What is its rationale and intent? What particular design issue or problem does it address?" [GoF, p6]
  • For providing a more structured and better comparable description of the intent, w3sDesign has introduced separate Problem and Solution sections.
    • The Problem section describes the key problems the design pattern can solve.
    • The Solution section describes how the design pattern solves the problems.
  • Hint: View how UML diagrams change when switching between sections or patterns.

Problem

The Strategy design pattern solves problems like:
How can a class be configured with an algorithm at run-time
instead of implementing an algorithm directly?
How can an algorithm be selected and exchanged at run-time?
See Applicability section for all problems Strategy can solve. See Solution section for how Strategy solves the problems.

  • An inflexible way is to implement (hard-wire) an algorithm directly within the class (Context) that requires (uses) the algorithm. Conditional statements (switch(…)) are needed to switch between different algorithms.
  • This commits (couples) the class to particular algorithms at compile-time and makes it impossible to change an algorithm later independently from (without having to change) the class. It makes the class more complex, especially if multiple algorithms are needed, and stops the class from being reusable if other algorithms are required.
    "Hard-wiring all such algorithms into the classes that require them isn't desirable for several reasons:" [GoF, p315]   "Algorithms are often extended, optimized, and replaced during development and reuse." [GoF, p24]
  • That's the kind of approach to avoid if we want to configure a class with an algorithm at run–time.
  • For example, reusable classes that support different algorithms.
    A reusable class should avoid implementing algorithms directly so that it can be configured with an algorithm at run-time.
  • For example, calculating prices in an order processing system.
    To calculate prices in different ways (depending on run-time conditions), it should be possible to select the right pricing algorithm at run-time (see Sample Code / Example 2).
  • For example, sorting objects.
    To sort objects in different ways, it should be possible to parameterize a sort operation with a compare algorithm (see Sample Code / Example 3).

Solution

The Strategy design pattern provides a solution:
Encapsulate an algorithm in a separate Strategy object.
A class delegates an algorithm to a Strategy object
instead of implementing an algorithm directly.
Describing the Strategy design in more detail is the theme of the following sections. See Applicability section for all problems Strategy can solve.

  • The key idea in this pattern is to implement algorithms in a separate inheritance hierarchy so that they can vary independently.
  • Define separate Strategy objects:
    • For all supported algorithms, define a common interface for performing an algorithm (Strategy | algorithm(…)).
    • Define classes (Strategy1,Strategy2,…) that implement the Strategy interface (encapsulate an algorithm [BGI]).
  • This enables compile-time flexibility (via inheritance).
    New algorithms can be added and existing ones can be changed independently by defining new (sub)classes.
  • A class (Context) delegates the responsibility for performing an algorithm to a Strategy object (strategy.algorithm(…)).
  • This enables run-time flexibility (via object composition).
    A class can be configured with a Strategy object, which it uses to per­form an algorithm, and even more, the Strategy object can be exchanged dynamically.

Background Information

  • Encapsulation is "The result of hiding a representation and imple­mentation in an object." [GoF, p360]
  • As a reminder, an object has an outside view (public interface/operations) and an inside view (private/hidden representation and implementation).
    Encapsulation means hiding a represen­tation and implementation in an object.
    Clients can only see the outside view of an object and are independent of any changes of an object's representation and implementation.
    That's the essential benefit of encapsulation.

    See also Design Principles.
  • Terms and Definitions
    • The term algorithm is usually defined as a procedure that takes some value as input, performs a finite number of steps, and produces some value as output.
      From a more general point of view, an algorithm is a piece of code.
    • "A responsibility denotes the obligation of an object to provide a certain behavior." [GB07, p600]
    • The terms responsibility, behavior, and functionality are usually interchangeable.

Motivation

Consider the left design (problem):

  • Hard-wired algorithms.
    • Different algorithms are implemented
      (hard-wired) directly within a class (Context).
    • This makes it impossible to add new algorithms or change existing ones independently from (without having to change) the Context class.
  • Conditional statements required.
    • Conditional statements are needed to switch between different algorithms.
  • Complicated classes.
    • Classes that include multiple algorithms get more complex and harder to implement, change, test, and reuse.

Consider the right design (solution):

  • Encapsulated algorithms.
    • Each algorithm is implemented (encapsulated) in a separate class (Strategy1,Strategy2,…).
    • This makes it easy to add new algorithms or change existing ones independently from (without having to change) the Context class.
  • No conditional statements required.
    • Conditional statements are replaced by delegating to different Strategy objects.
  • Simplified classes.
    • Classes that delegate an algorithm get less complex and easier to implement, change, test, and reuse.

Applicability

Design Problems

  • Exchanging Algorithms at Run-Time
    • How can a class be configured with an algorithm at run-time
      instead of implementing an algorithm directly?
    • How can an algorithm be selected and exchanged at run-time?
  • Flexible Alternative to Subclassing
    • How can a flexible alternative be provided to subclassing
      for changing an algorithm at compile-time?

Refactoring Problems [BGI]

  • Inflexible Code
    • How can hard-wired algorithms (compile-time implementation dependencies) be refactored?
  • Duplicated Code
    • How can algorithms that are duplicated in multiple places be refactored?
    • How can many related classes that differ only in their algorithms be replaced
      by a common class that is configured with one of many algorithms?
  • Complicated Code
    • How can conditional statements that switch between different algorithms be eliminated? Replace Conditional Logic with Strategy (129) [JK05]

Background Information

  • Refactoring and "Bad Smells in Code" [MF99] [JK05]
    • Code smells are certain structures in the code that "smell bad" and indicate problems that can be solved by a refactoring.
    • The most common code smells are:
      complicated code (including complicated/growing conditional code),
      duplicated code,
      inflexible code (that must be changed whenever requirements change), and
      unclear code (that doesn't clearly communicate its intent).

Structure

Static Class Structure

  • Context
    • Refers to the Strategy interface to perform an algorithm (strategy.algorithm())
      and is independent of how the algorithm is implemented.
    • Maintains a reference (strategy) to a Strategy object.
  • Strategy
    • For all supported algorithms, defines a common interface for performing an algorithm.
  • Strategy1,Strategy2,…
    • Implement the Strategy interface.

Dynamic Object Collaboration

  • In this sample scenario, a Context object delegates performing an algorithm to different Strategy objects.
    Let's assume that Context is configured with a Strategy1 object.
  • The interaction starts with the Context object that calls algorithm() on its installed Strategy1 object.
  • Strategy1 performs the algorithm and returns the result to Context.
  • Let's assume that Context changes its strategy to Strategy2 (because of run-time conditions such as reaching a threshold, for example).
  • Context now calls algorithm() on the Strategy2 object, which performs the algorithm and returns the result to Context.
  • There are different ways to select and change a strategy. For example, clients of Context might change the strategy or pass the strategy to the Context.
  • See also Sample Code / Example 1.

Consequences

Advantages (+)

  • Avoids compile-time implementation dependencies.
    • Clients refer to an interface (Strategy) and are independent of an implementation.
  • Provides a flexible alternative to subclassing.
    • Subclassing provides a way to change the algorithm of a class (at compile-time).
      When a subclass is instantiated, its algorithm is fixed and can't be changed for the life-time of the object.
    • Strategy provides a way to change the algorithm of an object (at run-time) by delegating to different Strategy objects.
  • Avoids conditional statements for switching between algorithms.
    • Conditional statements that switch between different algorithms are replaced by delegating to different Strategy objects.
    • "Code containing many conditional state­ments often indicates the need to apply the Strategy pattern." [GoF, p318]

Disadvantages (–)

  • Can make the common Strategy interface complex.
    • The Strategy interface may get complex because it must pass in the needed data for all supported algorithms (whether they are simple or complex; see Implementation).
  • Requires that clients understand how strategies differ.
    • "The pattern has a potential drawback in that a client must understand how Strategies differ before it can select the appropriate one. Clients might be exposed to implementation issues." [GoF, p318]
  • Introduces an additional level of indirection.
    • Strategy achieves flexibility by introducing an additional level of indirection (clients delegate an algorithm to a separate Strategy object), which makes clients dependent on a Strategy object.
    • This "can complicate a design and/or cost you some performance. A design pattern should only be applied when the flexibility it affords is actually needed." [GoF, p31]

Implementation

Implementation Issues

  • Implementation Variants
    • The Context and Strategy interfaces must be designed carefully so that the needed data can be passed/accessed efficiently and new algorithms can be added without having to extend an interface. There are two main variants:
  • Variant1: Push Data
    • Context passes the data to the strategy:
      strategy.algorithm(data1,data2,…)
    • The Strategy interface may get complex because it must pass in the needed data for all supported algorithms (whether they are simple or complex).
  • Variant2: Pull Data
    • Context passes nothing but itself to the strategy, letting strategy call back to get (pull) the required data from context:
      strategy.algorithm(this)
    • The Context interface may have to be extended to let strategies do their work and access the needed data.

Sample Code 1

Basic Java code for implementing the sample UML diagrams.

 1  package com.sample.strategy.basic;
 2  public class MyApp { 
 3      public static void main(String[] args) { 
 4          // Creating a Context object 
 5          // and configuring it with a Strategy1 object.
 6          Context context = new Context(new Strategy1());
 7          // Calling an operation on context.
 8          System.out.println("(1) " + context.operation());
 9          // Changing context's strategy.
10          context.setStrategy(new Strategy2());
11          System.out.println("(2) " + context.operation());
12      } 
13  } 
(1) Context: Delegating an algorithm to a strategy: Result = 1
(2) Context: Delegating an algorithm to a strategy: Result = 2

 1  package com.sample.strategy.basic;
 2  public class Context { 
 3      private Strategy strategy;
 4      
 5      public Context(Strategy strategy) { 
 6          this.strategy = strategy;
 7      } 
 8      public String operation() { 
 9          return "Context: Delegating an algorithm to a strategy: Result = " 
10                  + strategy.algorithm();
11      } 
12      public void setStrategy(Strategy strategy) { 
13          this.strategy = strategy;
14      } 
15  } 

 1  package com.sample.strategy.basic;
 2  public interface Strategy { 
 3      int algorithm();
 4  } 

 1  package com.sample.strategy.basic;
 2  public class Strategy1 implements Strategy { 
 3      public int algorithm() { 
 4          // Implementing the algorithm.
 5          return 1; // return result
 6      } 
 7  } 

 1  package com.sample.strategy.basic;
 2  public class Strategy2 implements Strategy { 
 3      public int algorithm() { 
 4          // Implementing the algorithm.
 5          return 2; // return result
 6      } 
 7  } 

Sample Code 2

Order Processing / Calculating order netto prices using different pricing strategies.

 1  package com.sample.strategy.order;
 2  import com.sample.data.*;
 3  public class Client { 
 4      // Running the Client class as application.
 5      public static void main(String[] args) { 
 6          // Creating a sales order object
 7          // and configuring it with a (default) pricing strategy.
 8          Order order = new SalesOrder(new PercentagePricingStrategy());
 9          // Creating products and order lines.
10          Product product1A = new SalesProduct("1A", "01", "Product1A", 100);
11          Product product1B = new SalesProduct("1B", "01", "Product1B", 200);
12          order.createOrderLine(product1A, 1);
13          order.createOrderLine(product1B, 1);
14          
15          System.out.println(
16              "(1) Total order brutto price .......................... : " +
17                  order.getPrice());
18          System.out.println(
19              "(2) using the default percentage strategy (10%) ....... : " +
20                  order.getNetPrice());
21          System.out.println(
22              "(3) changing to threshold strategy (10%; above 200: 20%): " +
23                  order.getNetPrice(new ThresholdPricingStrategy()));
24      } 
25  } 
(1) Total order brutto price .......................... : 300
(2) using the default percentage strategy (10%) ....... : 270
(3) changing to threshold strategy (10%; above 200: 20%): 240

 1  package com.sample.data;
 2  public interface Order {  // prices are in cents
 3      long getPrice();
 4      long getNetPrice();
 5      long getNetPrice(PricingStrategy strategy);
 6      void createOrderLine(Product product, int quantity);
 7  } 

 1  package com.sample.data;
 2  import java.util.ArrayList;
 3  import java.util.List;
 4  public class SalesOrder implements Order { 
 5      private List<OrderLine> orderLines = new ArrayList<OrderLine>();
 6      private PricingStrategy strategy;
 7      // Configuring sales order with a (default) strategy.
 8      public SalesOrder(PricingStrategy strategy) { 
 9          this.strategy = strategy;
10      } 
11      public long getPrice() { 
12          long total = 0;
13          for (OrderLine orderLine : orderLines) { 
14              total += orderLine.getPrice();
15          } 
16          return total;
17      } 
18      public long getNetPrice() { 
19          // Delegating the calculation to the default strategy.            
20          // Passing a reference to itself (this) so that strategy
21          // can act (call back) through the order interface.
22          return strategy.calculate(this);
23      } 
24      public long getNetPrice(PricingStrategy strategy) { 
25          // Delegating the calculation to the passed in strategy.            
26          return strategy.calculate(this);
27      } 
28      public void createOrderLine(Product product, int quantity) { 
29          orderLines.add(new SalesOrderLine(product, quantity));
30      } 
31  } 

 1  package com.sample.data;
 2  public interface PricingStrategy { 
 3      long calculate(Order order);
 4  } 

 1  package com.sample.data;
 2  public class PercentagePricingStrategy implements PricingStrategy { 
 3      public long calculate(Order order) { 
 4          // Calculating percentage ...
 5          int percentage = 10;
 6          //
 7          long amount = order.getPrice();
 8          long rabat = amount / 100 * percentage;
 9          return amount - rabat;
10      } 
11  } 

 1  package com.sample.data;
 2  public class ThresholdPricingStrategy implements PricingStrategy { 
 3      public long calculate(Order order) { 
 4          // Calculating threshold, percentage low/high ...
 5          long threshold = 200;
 6          short percentageLow = 10;
 7          short percentageHigh = 20;
 8          //
 9          long amount = order.getPrice();
10          if (amount < threshold)
11              return amount - amount / 100 * percentageLow;
12          else
13              return amount - amount / 100 * percentageHigh;
14      } 
15  } 

*******************************************************************
Other interfaces and classes used in this example.
*******************************************************************

 1  package com.sample.data;
 2  public interface OrderLine { 
 3      Product getProduct();
 4      int getQuantity();
 5      long getPrice();
 6  } 

 1  package com.sample.data;
 2  public class SalesOrderLine implements OrderLine { 
 3      private Product product;
 4      private int quantity;
 5      //
 6      public SalesOrderLine(Product product, int quantity) { 
 7          this.product = product;
 8          this.quantity = quantity;
 9      } 
10      public Product getProduct() { 
11          return product;
12      } 
13      public int getQuantity() { 
14          return quantity;
15      } 
16      public long getPrice() { 
17          return product.getPrice() * quantity;
18      } 
19  } 

 1  package com.sample.data;
 2  public interface Product { 
 3      void operation();
 4      String getId();
 5      String getGroup();
 6      String getDescription();
 7      long getPrice();
 8  } 

 1  package com.sample.data;
 2  public class SalesProduct implements Product { 
 3      private String id;
 4      private String group;
 5      private String description;
 6      private long price;
 7      // 
 8      public SalesProduct(String id, String group, String description, long price) { 
 9          this.id = id;
10          this.group = group;
11          this.description = description;
12          this.price = price;
13      } 
14      public void operation() { 
15          System.out.println("SalesProduct: Performing an operation ...");
16      } 
17      public String getId() { 
18          return id;
19      } 
20      public String getGroup() { 
21          return group;
22      } 
23      public String getDescription() { 
24          return description;
25      } 
26      public long getPrice() { 
27          return price;
28      } 
29  } 

Sample Code 3

Sorting customers using different compare strategies.

Customer Test Data:
ID Name---------------- PhoneNumber--- Birthday--
01 FirstName1 LastName1 (001) 002-0002 03.03.1980
02 FirstName3 LastName3 (001) 003-0003 01.01.1970
03 FirstName2 LastName2 (002) 001-0001 02.02.1980
PhoneNumber = (areaCode) + prefix + lineNumber.
 1  package com.sample.strategy.sort;
 2  import java.util.Comparator; // = Strategy (compare algorithm)
 3  import com.sample.data.Customer;
 4  import com.sample.data.Customers;
 5  import java.util.Collections;
 6  import java.util.List;
 7  public class Client { 
 8      // Running the Client class as application.
 9      public static void main(String[] args) throws Exception { 
10          // Creating the customers.
11          List<Customer> customerList = Customers.createTestData(3);
12          
13          System.out.println(
14              "SORTING CUSTOMERS:\n\n" +
15              "(1) by using the default comparator \n" +
16              "    = according to the customer ID: ");
17          Collections.sort(customerList);
18          System.out.println(customerList);
19           
20          System.out.println("\n" +
21              "(2) by specifying the NAME comparator \n" +
22              "    = according to the customer name: ");
23          Collections.sort(customerList, Customers.NAME);
24          System.out.println(customerList);
25          
26          // Implementing individual requirements directly, for example:
27          System.out.println("\n" +
28              "(3) by implementing the comparator directly \n" +
29              "    = according to the (area code) of the customer phone number \n" +
30              "      and the customer name: ");
31          Collections.sort(customerList, new Comparator<Customer>() {  // inner class
32                  public int compare(Customer c1, Customer c2) { 
33                      // Implementing the comparator interface / compare().
34                      if (c1.getPhoneNumber().getAreaCode() <
35                      c2.getPhoneNumber().getAreaCode()) return -1;
36                      if (c1.getPhoneNumber().getAreaCode() >
37                      c2.getPhoneNumber().getAreaCode()) return 1;
38                      // Area codes are equal, compare names:
39                      // getName() returns an object of type Name;
40                      // compareTo() implemented in the Name class. 
41                      return (c1.getName().compareTo(c2.getName()));
42                  } 
43              } );
44          System.out.println(customerList);
45          
46          System.out.println("\n" +
47              "(4) by specifying the BIRTHDAY comparator \n" +
48              "    = according to the customer birthday descending: ");
49          Collections.sort(customerList, Customers.BIRTHDAY);
50          System.out.println(customerList);
51      } 
52  } 
SORTING CUSTOMERS:

(1) by using the default comparator 
    = according to the customer ID: 
[
Customer: 1  FirstName1  LastName1  (001) 002-0002  03.03.1980, 
Customer: 2  FirstName3  LastName3  (001) 003-0003  01.01.1970, 
Customer: 3  FirstName2  LastName2  (002) 001-0001  02.02.1980]

(2) by specifying the NAME comparator 
    = according to the customer name: 
[
Customer: 1  FirstName1  LastName1  (001) 002-0002  03.03.1980, 
Customer: 3  FirstName2  LastName2  (002) 001-0001  02.02.1980, 
Customer: 2  FirstName3  LastName3  (001) 003-0003  01.01.1970]

(3) by implementing the comparator directly 
    = according to the (area code) of the customer phone number 
      and the customer name: 
[
Customer: 1  FirstName1  LastName1  (001) 002-0002  03.03.1980, 
Customer: 2  FirstName3  LastName3  (001) 003-0003  01.01.1970, 
Customer: 3  FirstName2  LastName2  (002) 001-0001  02.02.1980]

(4) by specifying the BIRTHDAY comparator 
    = according to the customer birthday descending: 
[
Customer: 1  FirstName1  LastName1  (001) 002-0002  03.03.1980, 
Customer: 3  FirstName2  LastName2  (002) 001-0001  02.02.1980, 
Customer: 2  FirstName3  LastName3  (001) 003-0003  01.01.1970]

 1  package java.util;
 2  // From the Java Language = Strategy (compare algorithm).
 3  public interface Comparator<T> {  
 4      /** 
 5       * The compare method must be implemented to compare 
 6       * two objects for order:   
 7       * returns a negative integer, zero, or a positive integer 
 8       * as the first argument is less than, equal to, 
 9       * or greater than the second.
10       */ 
11      int compare(T object1, T object2);   
12      // ...
13  } 

 1  package com.sample.data;
 2  import java.util.Comparator; 
 3  import java.util.List;
 4  import java.util.ArrayList;
 5  import java.util.Date;
 6  import java.text.SimpleDateFormat;
 7  import java.text.ParseException;
 8  //
 9  // This is a non-instantiable class that holds (public)
10  // static utility methods needed for handling customers.
11  //
12  public class Customers { 
13      private static final SimpleDateFormat dateFormatter =
14          new SimpleDateFormat("dd.MM.yyyy");
15      private Customers() { } 
16      // NAME = reference to a comparator object.
17      public static final Comparator<Customer> NAME =
18          new Comparator<Customer>() {  // inner class
19              // Implementing the comparator interface / compare().
20              public int compare(Customer c1, Customer c2) { 
21                  // compareTo() implemented in the Name class. 
22                  return c1.getName().compareTo(c2.getName());
23              } 
24          } ;
25      // PHONENUMBER = reference to a comparator object.
26      public static final Comparator<Customer> PHONENUMBER =
27          new Comparator<Customer>() {  // inner class
28              // Implementing the comparator interface / compare().
29              public int compare(Customer c1, Customer c2) { 
30                  // getPhoneNumber() returns an object of type PhoneNumber;
31                  // compareTo() implemented in the PhoneNumber class.
32                  return c1.getPhoneNumber().compareTo(c2.getPhoneNumber());
33              } 
34          } ;
35      // BIRTHDAY = reference to a comparator object.
36      public static final Comparator<Customer> BIRTHDAY =
37          new Comparator<Customer>() {  // inner class
38              // Implementing the comparator interface / compare().
39              public int compare(Customer c1, Customer c2) { 
40                  // compareTo() implemented in the Date class (Java platform). 
41                  return c2.getBirthday().compareTo(c1.getBirthday());
42              } 
43          } ;
44      //
45      public static void checkData(int id, Name name, PhoneNumber pn, Date birthday) throws ParseException { 
46          if (id < 0)
47              throw new IllegalArgumentException("Customer ID is negative");
48          if (birthday.compareTo(dateFormatter.parse("01.01.1900")) < 0 ||
49              birthday.compareTo(dateFormatter.parse("01.01.2000")) > 0)
50              throw new IllegalArgumentException("Birthday before 1900 or after 2000");
51          // ...
52      } 
53      public static List<Customer> createTestData(int size) throws Exception { 
54          List<Customer> customerList = new ArrayList<Customer>(size);
55          customerList.add(new Customer1(1,
56              new Name("FirstName1", " LastName1"),
57              new PhoneNumber(1, 2, 2), dateFormatter.parse("03.03.1980")));
58          customerList.add(new Customer1(2,
59              new Name("FirstName3", " LastName3"),
60              new PhoneNumber(1, 3, 3), dateFormatter.parse("01.01.1970")));
61          customerList.add(new Customer1(3,
62              new Name("FirstName2", " LastName2"),
63              new PhoneNumber(2, 1, 1), dateFormatter.parse("02.02.1980")));
64          return customerList;
65      } 
66  } 

 1  package com.sample.data;
 2  import java.util.Date;
 3  public interface Customer extends Comparable<Customer> { 
 4      int getId();
 5      Name getName();
 6      PhoneNumber getPhoneNumber();
 7      Date getBirthday();
 8  } 

 1  package com.sample.data;
 2  import java.text.SimpleDateFormat;
 3  // Skeletal implementation of the customer interface.
 4  import java.util.Date;
 5  public abstract class AbstractCustomer implements Customer { 
 6      private final int id;
 7      private final Name name;
 8      private final PhoneNumber phoneNumber;
 9      private final Date birthday;
10      private static final SimpleDateFormat dateFormatter =
11          new SimpleDateFormat("dd.MM.yyyy");
12      // TODO Check
13      protected AbstractCustomer(int id, Name name, PhoneNumber pn, Date birthday) throws Exception { 
14          Customers.checkData(id, name, pn, birthday);
15          this.id = id;
16          this.name = name;
17          this.phoneNumber = pn;
18          this.birthday = birthday;
19      } 
20      @Override
21      public boolean equals(Object o) { 
22          if (o == this) return true;
23          if (!(o instanceof Customer)) return false;
24          Customer c = (Customer) o;
25          return c.getId() == id;
26      } 
27      @Override
28      public int hashCode() { 
29          int result = 17;
30          result = 31 * result + id;
31          return result;
32      } 
33      @Override
34      public String toString() { 
35          return "\nCustomer: " + id + "  " + name + "  " + phoneNumber + "  " +
36              dateFormatter.format(birthday);
37      } 
38      // The compareTo method implements the Comparable interface. 
39      // It defines the "natural ordering" (default ordering).
40      public int compareTo(Customer c) { 
41          if (id < c.getId()) return -1;
42          if (id > c.getId()) return 1;
43          // All fields are equal.
44          return 0;
45      } 
46      //
47      public int getId() { 
48          return id;
49      } 
50      public Name getName() { 
51          return name;
52      } 
53      public PhoneNumber getPhoneNumber() { 
54          return phoneNumber;
55      } 
56      public Date getBirthday() { 
57          return birthday;
58      } 
59  } 

 1  package com.sample.data;
 2  import java.util.Date;
 3  public class Customer1 extends AbstractCustomer { 
 4      public Customer1(int id, Name name, PhoneNumber pn, Date birthday) throws Exception { 
 5          super(id, name, pn, birthday);
 6          // ...
 7      } 
 8      // ...
 9  } 

*******************************************************
Other classes used in this example.
*******************************************************

 1  package com.sample.data;
 2  public class Name implements Comparable<Name> { 
 3      private final String firstName;
 4      private final String lastName;
 5      // ...
 6      public Name(String firstName, String lastName) { 
 7          if (firstName == null || lastName == null)
 8              throw new NullPointerException();
 9          this.firstName = firstName;
10          this.lastName = lastName;
11      } 
12      @Override
13      public boolean equals(Object o) { 
14          if (!(o instanceof Name)) return false;
15          Name name = (Name) o;
16          return name.firstName.equals(firstName)
17              && name.lastName.equals(lastName);
18      } 
19      @Override
20      public int hashCode() { 
21          return 31 * firstName.hashCode() + lastName.hashCode();
22      } 
23      @Override
24      public String toString() { 
25          return firstName + " " + lastName;
26      } 
27      // The compareTo method implements the Comparable interface. 
28      // It defines the "natural ordering" (default ordering).
29      public int compareTo(Name name) { 
30          int cmp = lastName.compareTo(name.lastName);
31          if (cmp != 0) return cmp;
32          // Last names are equal, compare first names.
33          return firstName.compareTo(name.firstName);
34      } 
35      //
36      public String getFirstName() { 
37          return firstName;
38      } 
39      public String getLastName() { 
40          return lastName;
41      } 
42  } 

 1  // Based on Joshua Bloch / Effective Java / Item 9,10, and 12. 
 2  package com.sample.data;
 3  public class PhoneNumber implements Comparable<PhoneNumber> { 
 4      private final short areaCode;
 5      private final short prefix;
 6      private final short lineNumber;
 7      public PhoneNumber(int areaCode, int prefix, int lineNumber) { 
 8          rangeCheck(areaCode, 999, "area code");
 9          rangeCheck(prefix, 999, "prefix");
10          rangeCheck(lineNumber, 9999, "line number");
11          this.areaCode = (short) areaCode;
12          this.prefix = (short) prefix;
13          this.lineNumber = (short) lineNumber;
14      } 
15      private static void rangeCheck(int arg, int max, String name) { 
16          if (arg < 0 || arg > max)
17              throw new IllegalArgumentException(name + ": " + arg);
18      } 
19      @Override
20      public boolean equals(Object o) { 
21          if (o == this) return true;
22          if (!(o instanceof PhoneNumber)) return false;
23          PhoneNumber pn = (PhoneNumber) o;
24          return pn.lineNumber == lineNumber
25              && pn.prefix == prefix
26              && pn.areaCode == areaCode;
27      } 
28      @Override
29      public int hashCode() { 
30          int result = 17;
31          result = 31 * result + areaCode;
32          result = 31 * result + prefix;
33          result = 31 * result + lineNumber;
34          return result;
35      } 
36      /**
37       * Returns the string representation of this phone number. The string
38       * consists of 14 characters whose format is "(XXX) YYY-ZZZZ", where XXX is
39       * the area code, YYY is the prefix, and ZZZZ is the line number.
40       */
41      @Override
42      public String toString() { 
43          return String.format("(%03d) %03d-%04d",
44              areaCode, prefix, lineNumber);
45      } 
46      // The compareTo method implements the Comparable interface. 
47      // It defines the "natural ordering" (default ordering).
48      public int compareTo(PhoneNumber pn) { 
49          if (areaCode < pn.areaCode) return -1;
50          if (areaCode > pn.areaCode) return 1;
51          // Area codes are equal, compare prefixes.
52          if (prefix < pn.prefix) return -1;
53          if (prefix > pn.prefix) return 1;
54          // Area codes and prefixes are equal, compare line numbers.
55          if (lineNumber < pn.lineNumber) return -1;
56          if (lineNumber > pn.lineNumber) return 1;
57          // All fields are equal.
58          return 0;
59      } 
60      //
61      public int getAreaCode() { 
62          return areaCode;
63      } 
64      public int getPrefix() { 
65          return prefix;
66      } 
67      public int getLineNumber() { 
68          return lineNumber;
69      } 
70  }