Java Programming/Design Patterns

From Wikibooks, open books for an open world
Jump to navigation Jump to search

A design pattern is not a finished design, it is a description of a solution to a common problem. A design pattern can be reused in multiple applications, and that is the main advantage of using it. It can also be seen as a template for how to solve a problem that can occur in many different situations and/or applications. It is not code reuse as it usually does not specify code, but code can be easily created from a design pattern. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

Each design pattern consists of the following parts:

To create a design pattern, we need to go through a mini analysis design and may be coding to test out the solution. This section state the requirements the problem we want to solve. This is usually a common problem that will occur in more than one application.
This section states the technological boundaries, that helps and guides the creation of the solution.
This section describes how to write the code to solve the above problem. This is the design part of the design pattern. It may contain class diagrams, sequence diagrams, and or whatever is needed to describe how to code the solution.

A design pattern can be considered as block that can be placed in your design document, and you have to implement the design pattern with your application.

Using design patterns speeds up your design and helps to communicate your design to other team members.

Terminology[edit | edit source]

The design patterns are not always simple to understand as it is a theoretical vision of programming. You must distinguish the abstraction and the representation. For example, we have a method that implements an addition:

    public int add(int a, int b) {
        return a + b;
  • The abstraction is only the visible part of your code outside. It is the contract between the provider and the client code. In Java, this theoretical concept is mostly the signatures of the methods of a class or an interface.
  • The representation is the way a problem is resolved. It follows the contract of what is given as input and what is expected to be returned. In Java, this theoretical concept is mostly the code lines in a class and any internal calls to other methods or classes.
    public abstract int add(int a, int b);
    public int add(int a, int b) {
        return a + b;
abstraction representation