An example of method level generic type usage

This example shows how to use generic type in a design pattern.
The following code will structure a process to separate logic code from routine tasks.

First, create an interface and an unimplemented method, which will be called in Executor class:

public interface Executable<T> { T execute(); }

Second, code the routine tasks, and insert the logic to be execute:

public class Executor {
    public <T> T process(Executable<T> e) {
        //pre execution. e.g.: start transaction
        T t = e.execute();
        //post execution. e.g.: commit transaction, close resource etc.
        return t;

Finally, call the Executor to process your task, and code the business logic:

public class Caller {
    public static void main(String args[]) {
        DeterminedType t = new Executor().process(() -> {
            //code to deal with the business logic
            return result; //the type of the result returning here will determine the type of t

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s