[Java] Design Pattern:Code Shape - manage your code shape

来源:https://www.cnblogs.com/steven-yang/archive/2018/04/26/8954782.html
-Advertisement-
Play Games

[Java] Design Pattern:Code Shape manage your code shape Code Shape Design Pattern Here I will introduce a design pattern: Code Shape。 It's fine that y ...


[Java] Design Pattern:Code Shape - manage your code shape

Code Shape Design Pattern

Here I will introduce a design pattern: Code Shape。
It's fine that you never heard that, I just created it.

Usage

In the enterprise application development, in most cases, we adopt multiple layers architectures.
Methods in each layer tend to present the same code structure. Here we name it as code shape.
For example, in the database access layer, writing methods would have following code:

  • Get the database connection.
  • Begin a transaction.
  • Write database.
  • Commit the transaction.
  • When there is an exception, rollback the transaction.

Beside, some times, architects hope to add some infrastructure functions, e.g.

  • Unified processing authority authentication.
  • Unified handling exceptions.
  • Logging.
  • Profiling for performance.
  • Logging method parameters.

So, the design pattern code shape implements the above requirements by using Java lambda expressions
Provide a flexible way to manage every method shape in a layer.

Code Demonstrate

This article presents a code demonstrate to implement following features:

  • Before calling a method, write a log
  • Log method parameters
  • After calling the method, write a log
  • If applicable, log the return value
  • When there is an exception, log the exception

Prerequisites

About Java 8 Lambda Expressions, please see here.

Java provides java.util.function.Consumer and java.util.function.Function, to benefit us a convenience way to use lambda expressions.

Consumer can be used by non-return methods, and Function can be used by methods which have return.
Unfortunately, they only support one argument.
Therefore, if need, we have to write interfaces to support multiple arguments.
Here are samples to support tow input arguments:

  • ConsumerTwo
@FunctionalInterface
public interface ConsumerTwo<T, T2> {
    public void accept(T t, T2 t2);
}
  • FunctionTwo
@FunctionalInterface
public interface FunctionTwo<T, T2, R> {
    public R apply(T t, T2 t2);
}

Annotation FunctionalInterface indicates this is a function interface, only one method is defined inside.

Main class code

The main class calls 3 samples:
The first sample: it is a method without return.
The second sample: it is a method without return, but always throw an exception.
The third sample: it is a method with return.

Code:

  • Main.java
public class Main {
    public static void main(String[] args) {
        
        pattern.CodeShapeSample br = new pattern.CodeShapeSample();

        // call business rule one
        br.businessRuleOne("Jack", "is man");

        // call business rule two, will get an exception
        try {
            br.businessRuleTwoThrowException("Tom", "is woman");
        }
        catch (Exception e) {}

        // call business rule three which has a return.
        String value = br.businessRuleThree("Mary", "is woman");
    }
}

Code Shape Design Pattern Code

  • CodeShapeSample
package pattern;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public class CodeShapeSample {
    
    /*
     * This is a consumer sample
     */
    public void businessRuleOne(final String name, final String value) {
        
        CodeShapePattern.consumerShape.accept((o) -> {
            // here is business rule logical
            System.out.println("here is business rule logical 1.");
        }, Arrays.asList(name, value));
    }
    
    /*
     * This is a consumer with exception sample
     */
    public void businessRuleTwoThrowException(final String name, final String value) {
        
        CodeShapePattern.consumerShape.accept((o) -> {
            // here is business rule logical
            System.out.println("here is business rule logical 2.");
            throw new RuntimeException("failure!");
        }, Arrays.asList(name, value));
    }
    
    /*
     * This is a function sample
     */
    public String businessRuleThree(final String name, final String value) {
        
        return CodeShapePattern.<String>getFunctionShape().apply((o) -> {
            // here is business rule logical
            System.out.println("here is business rule logical 3.");
            return name + " " + value;
        }, Arrays.asList(name, value));
    }
}
  • CodeShapePattern
package pattern;

import java.text.MessageFormat;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public class CodeShapePattern {

    public static ConsumerTwo<Consumer<Object>, List<Object>> consumerShape = (body, params) -> 
    {
        StackTraceElement caller = new Exception().getStackTrace()[2];
        String method = caller.getClassName() + "#" + caller.getMethodName();
        try {
            System.out.println("");
            System.out.println("========");
            System.out.println(MessageFormat.format("start method ''{0}''", method));
            if (params != null) {
                for(Object param : params) {
                    System.out.println(MessageFormat.format("parameter : ''{0}''", param.toString()));
                }
            }
            
            System.out.println("---- start body ----");
            body.accept(null);
            System.out.println("---- end body ----");
        }
        catch (Exception e) {
            System.out.println(MessageFormat.format("error method ''{0}'': {1}", method, e.getMessage()));
            throw e;
        }
        finally {
            System.out.println(MessageFormat.format("end method ''{0}''", method));
        }
    };
    
    public static <R> FunctionTwo<Function<Object, R>, List<Object>, R> getFunctionShape() {
        FunctionTwo<Function<Object, R>, List<Object>, R> function = (body, params) -> 
        {
            R ret = null;
            StackTraceElement caller = new Exception().getStackTrace()[2];
            String method = caller.getClassName() + "#" + caller.getMethodName();
            try {
                System.out.println("");
                System.out.println("========");
                System.out.println(MessageFormat.format("start method ''{0}''", method));
                if (params != null) {
                    for(Object param : params) {
                        System.out.println(MessageFormat.format("parameter : ''{0}''", param.toString()));
                    }
                }
                
                System.out.println("---- start body ----");
                ret = body.apply(null);
                System.out.println("---- end body ----");
            }
            catch (Exception e) {
                System.out.println(MessageFormat.format("error method ''{0}'': {1}", method, e.getMessage()));
                throw e;
            }
            finally {
                System.out.println(MessageFormat.format("end method ''{0}'', return ''{1}''", method, ret.toString()));
            }
            return ret;
        };
        
        return function;
    }
}

Explanation 1:using Consumer

OK. All code is presented, let's explain them.

  • Business Rule Code
    As this business rule method does not return any thing, so I use CodeShapePattern.consumerShape.
    There are 2 input parameters.: business rule logical and the method's parameter values.
    /*
     * This is a consumer sample
     */
    public void businessRuleOne(final String name, final String value) {
        
        CodeShapePattern.consumerShape.accept((o) -> {
            // here is business rule logical
            System.out.println("here is business rule logical 1.");
        }, Arrays.asList(name, value));
    }
  • Code Shape Design Pattern Code - Consumer
    We can see it, the consumerShape is a static variable that implements unified functions.
    This consumerShape uses a nested Consumer.
    The Consumer inside is the business rule logical., In business rule methods, you can write any code what you want.
    BTW, the input parameter is useless, we may define a ConsumerZero interface to simplify the code.
    public static ConsumerTwo<Consumer<Object>, List<Object>> consumerShape = (body, params) -> 
    {
        StackTraceElement caller = new Exception().getStackTrace()[2];
        String method = caller.getClassName() + "#" + caller.getMethodName();
        try {
            System.out.println("");
            System.out.println("========");
            System.out.println(MessageFormat.format("start method ''{0}''", method));
            if (params != null) {
                for(Object param : params) {
                    System.out.println(MessageFormat.format("parameter : ''{0}''", param.toString()));
                }
            }
            
            System.out.println("---- start body ----");
            body.accept(null);
            System.out.println("---- end body ----");
        }
        catch (Exception e) {
            System.out.println(MessageFormat.format("error method ''{0}'': {1}", method, e.getMessage()));
            throw e;
        }
        finally {
            System.out.println(MessageFormat.format("end method ''{0}''", method));
        }
    };

Less code version:

    public static ConsumerTwo<Consumer<Object>, List<Object>> consumerShape = (body, params) -> 
    {
        try {
            body.accept(null);
        }
        catch (Exception e) {
            throw e;
        }
        finally {
        }
    };

Explanation 2: Using Function

  • Business Rule Layer method
    As this business rule layer method has return, we use CodeShapePattern.<R>getFunctionShape() inside.
    getFunctionShape() is a generic method, the generic type is the return type of the business rule method.
    There are 2 parameters:
    The first: business rule logical, with return.
    The second: parameters of the business rule method, for internal use.
    /*
     * This is a function sample
     */
    public String businessRuleThree(final String name, final String value) {
        
        return CodeShapePattern.<String>getFunctionShape().apply((o) -> {
            // here is business rule logical
            System.out.println("here is business rule logical 3.");
            return name + " " + value;
        }, Arrays.asList(name, value));
    }
  • Code Shape Design Pattern - Function
    Different as the consumerShape, getFunctionShape is a static generic method that implements unified functions.
    This getFunctionShape uses a nested Function.
    The Function inside is the business rule logical., In business rule methods, you can write any code what you want.
    BTW, the input parameter is useless, we may define a FunctionZero interface to simplify the code.
    public static <R> FunctionTwo<Function<Object, R>, List<Object>, R> getFunctionShape() {
        FunctionTwo<Function<Object, R>, List<Object>, R> function = (body, params) -> 
        {
            R ret = null;
            StackTraceElement caller = new Exception().getStackTrace()[2];
            String method = caller.getClassName() + "#" + caller.getMethodName();
            try {
                System.out.println("");
                System.out.println("========");
                System.out.println(MessageFormat.format("start method ''{0}''", method));
                if (params != null) {
                    for(Object param : params) {
                        System.out.println(MessageFormat.format("parameter : ''{0}''", param.toString()));
                    }
                }
                
                System.out.println("---- start body ----");
                ret = body.apply(null);
                System.out.println("---- end body ----");
            }
            catch (Exception e) {
                System.out.println(MessageFormat.format("error method ''{0}'': {1}", method, e.getMessage()));
                throw e;
            }
            finally {
                System.out.println(MessageFormat.format("end method ''{0}'', return ''{1}''", method, ret.toString()));
            }
            return ret;
        };
        
        return function;
    }

Less code version:

    public static <R> FunctionTwo<Function<Object, R>, List<Object>, R> getFunctionShape() {
        FunctionTwo<Function<Object, R>, List<Object>, R> function = (body, params) -> 
        {
            R ret = null;

            try {
                ret = body.apply(null);
            }
            catch (Exception e) {
                throw e;
            }
            finally {
            }
            return ret;
        };
        
        return function;
    }

Output result


========
start method 'pattern.CodeShapeSample#businessRuleOne'
parameter : 'Jack'
parameter : 'is man'
---- start body ----
here is business rule logical 1.
---- end body ----
end method 'pattern.CodeShapeSample#businessRuleOne'

========
start method 'pattern.CodeShapeSample#businessRuleTwoThrowException'
parameter : 'Tom'
parameter : 'is woman'
---- start body ----
here is business rule logical 2.
error method 'pattern.CodeShapeSample#businessRuleTwoThrowException': failure!
end method 'pattern.CodeShapeSample#businessRuleTwoThrowException'

========
start method 'pattern.CodeShapeSample#businessRuleThree'
parameter : 'Mary'
parameter : 'is woman'
---- start body ----
here is business rule logical 3.
---- end body ----
end method 'pattern.CodeShapeSample#businessRuleThree', return 'Mary is woman'

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 頁面滾動插件 finger-mover https://github.com/HcySunYang/finger-mover https://fmover.hcysun.me/#/zh-cn/plugins/simulation-scroll-y 封裝vue組件 https://github.com ...
  • 一,使用jquery和使用vue的區別 二,對MVVM的理解 三,vue中如何實現響應式 四,vue如何解析模版 五,vue整個實現流程 一,使用jquery和使用vue的區別 jquery實現todo-list <!DOCTYPE html> <html lang="en"> <head> <me ...
  • 以前排版排的比較少,沒有設計圖的那種,我們後端一般都是用框架或者仿照樣式,最近公司需要定製一個企業站,要還原設計稿。我在排版中大量用到了垂直居中與水平居中。 1,傳統的水平居中(固定寬度居中),如一個div,寬1200 2,水平與垂直居中,網上有很多種方式,我現在用的是這種方式 這個方法使用絕對定位 ...
  • 組件: ng g component component/demo 服務: ng g service service/news 然後在app.module.ts里引入 ng g service service/news --module=app 在創建服務時候在後面加上 --module=app 就 ...
  • 1.首先,下載xampp,安裝按預設勾選即可。 2.安裝完成後,啟動Apache和MySQL這兩個服務。 啟動後變成綠色,表示啟動成功。 3.點擊MySQL項的Admin進入資料庫後臺。 4.點擊用戶賬戶新建用戶。 5.填寫用戶名,host name選本地,生成密碼,用戶名密碼用文本保留好。 5.選 ...
  • 在anular4更新到angular5後,有些模塊也發生了有些變化,例如http模塊。 首先在app.module.ts裡面引入HttpClientModule import { HttpClientModule } from '@angular/common/http'; 在組件使用的時候引入: ...
  • jQuery length和size()區別總結如下: 1.length是屬性,size()是方法。 2.如果你只是想獲取元素的個數,兩者效果一樣既 $("img").length 和 $("img").size() 獲取的值是一樣的。 3.如果計算一個字元串的長度或者計算一個數組元素的個數就只得用 ...
  • 首先請原諒本文標題取的有點大,但並非為了嘩眾取寵。本文取這個標題主要有3個原因,這也是寫作本文的初衷: (1)目前國內幾乎搜索不到全面講解如何搭建前後端分離框架的文章,講前後端分離框架思想的就更少了,而筆者希望在本文中能夠全面、詳細地闡述我們團隊在前後端分離的摸索中所得到的搭建思路、最佳實踐以及架構 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...