Interface allows any objects with the required methods to use a piece of code. Implementing an interface makes the class a subtype of the interface.
See Polymorphism.java. Using List<Integer> list = new ArrayList<>();
instead of ArrayList<Integer> list = new ArrayList<>();
is a good practice because it gives you the flexibility to, for example, use a LinkedList instead.
A factory is simply a method whose role is to create and return an object. Several of the following design patterns rely on this concept.
See Factory.java, they can allow multiple constructor with same parameter but with more descriptive method header.
Implement Iterable <T>
in your class which returns an interator. An iterator is an implementation of Iterator<T>
(See inner class)
See IterUse.java.
The purpose is to provide access to a collection of encapsulated object without exposing the underlying representation.
See IterPattern.java The best way to use Iterable is to return the Iterator implementation of the data structure (ex: ArrayList)
Goal: allow switching algorithm.
An example of the strategy design pattern is Collection.sort()
which allows the client to use a custom comparison algorithm.
See Strategy.java. You can either sort the items by name or by price.
Strategy design pattern where the strategy is an interface which the client is responsible for implementing.
Client should not be forced to implement interfaces it does not need. An interface should only contain methods that are often used together.