Design Pattern Overview

What is design pattern

Design pattern is a set of conclusive solutions to those frequently appeared problems.

Why design pattern

The design patterns help you to write flexible, low-coupled, high-cohesive code.

How to learn design patterns

In stead of think design pattern as a technical thing, try to think it as art. Actually it is art.

Learn design pattern in following ways
1. Motivation(what is cons of not using this pattern, real use case as example)

2. Implementation(how to implement pattern in code level)

3. Pros and cons

4. Pattern correlations(how patterns are similar to each other, and how patterns can work together)

Types of design pattern

There are three types of design patterns:

  1. Creational Design Pattern
    1. Creational Design Pattern is used for initializing object. They gives you a lot of flexibility to control how/when/what object is created.
  2. Structural Design Pattern
    1. Give people a better reasons to do modularization.
    2. Structural Design Pattern is a set of solutions of how to composite and arrange classes together to have better flexibility to fix with each other and to be extended.
  3. Behavioral Design Pattern
    1. Behavioral Design Pattern is a set of design patterns that decide how the responsibility is assigned between different classes, as well as how different classes can talk to each other. Therefore, we can build a really complex system with a lot of simple classes.

Java – CompletableFuture

CompletableFuture interface is in Java 8 or later, before Java 8 there’s only Future interface.

Future interface provider developers ability to run async tasks. It provides two method: isDone() and get().

  • isDone() method returns a boolean value indicates that whether the task run asynchrounsly is completed or not.
  • get() method get the value returned from async task once it’s done. This will block the current thread.

The motivation to have completable future is that Future interface is insufficient in the following cases.

  1.  Future interface do not provide functionality to manually complete the async task.
  2.  Future interface do not provide functionality to have callback function, meaning we are not notified when async task finishes, and we cannot do stuff once the async task finishes.

CompletableFuture has many methods to support the above disadvantages. Now let’s look at some most used methods of CompletableFuture.

complete()

With this method, we can manually complete the async task.

CompletableFuture future = new CompletableFuture();
future.complete("Manually complete task.");

 

CompletableFuture provides us two method to set callback function for async task: supplyAsync() and runAsync(). The different is that supplyAsync() will return value, and runAsync() just run an async task. Let’s look at the code.

supplyAsync()