Hello, I’m Xiaoning

In the past half a month, I worked with many tool classes, and found that although these tool classes have different functions, their encapsulation ideas and organization methods are very similar, and some common things can be extracted, which is worth sharing.

It is better to teach a man to fish than to teach a man to fish. You may not learn a few lines of code from my article, but believe me, the harvest is more than the code

Tool Class Case

First take a look at my results during this period of time (the installation package has not been released online, you can ask me to get the installation package)

Sample tool class source code

I selected several toolkits to display, it can be seen that the composition of a tool is roughly composed of three types: 1. XxxConfig. 2. Xxxtools. 3. Model package, which stores the request/return entity of the tool

Let’s take the stapled tool kit as an example:

DingConfig.java

Public class DingConfig {// Pin the url obtained when adding robots private String URL; // Secret private String secret; // Add some parameters to the original URL public StringgetUrl() {        Long timestamp = System.currentTimeMillis();        String sign = getSign(timestamp);        return url+"X tamp ="+timestamp+"&sign="+sign; */ public String getSign(Long timestamp) {try {String stringToSign = timestamp +"\n" + secret;            Mac mac = Mac.getInstance("HmacSHA256");            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));            return URLEncoder.encode(Base64.getEncoder().encodeToString(signData), "UTF-8");        }catch (Exception e){            returnnull; }}}Copy the code

As shown above, we can see that the configuration class does not only store values, but also some common configuration-related functions, which is a bit like the domain-driven congested entity class.

Dingmessage.java has stripped away the relevant GET /set methods

Public class DingMessage {// Define the type of the pin message. Public static final String TYPE_TEXT="text"; Public static final String TYPE_ACTION_CARD = public static final String TYPE_ACTION_CARD ="actionCard"; private String msgtype; private TextMessage text; private ActionCardMessage actionCard; Static class TextMessage{private String content; public StringgetContent() {            returncontent; Static class ActionCardMessage{private String title; private String text; private String hideAvatar; private String btnOrientation; private List<DButton> btns; Static class DButton{private String title; private String actionURL; } public static DingMessage initTextMessage(String Content){public static DingMessage initTextMessage(String content){ TextMessage textMessage = new TextMessage(); textMessage.content = content; DingMessage dingMessage = new DingMessage(); dingMessage.text = textMessage; dingMessage.msgtype = TYPE_TEXT;returndingMessage; }}Copy the code

We interact with third parties through JSON. Either map to JSON, or entity class to JSON. Here I always use entity class to JSON, and I don’t split many entity classes, directly through the static inner class can complete the entity organization

DingTools.java

Public static void sendText(String Content,DingConfig config){// Construct request entity class DingMessage message = DingMessage.initTextMessage(content); S = json.tojsonString (message); HttpResponse<String> response = httpTools.dopost (config.geturl (),s, httprequest.json_header, string.class); System.out.println(response.getBody())); }Copy the code

As shown in the source code above, the tool class is roughly divided into four steps, construct request entity class, transform into JSON, request, and then process the return value, the same to request wechat/Redis, is also roughly this structure

The caller

Public static void main(String[] args) {config DingConfig config = new DingConfig(); config.setUrl("https://oapi.dingtalk.com/robot/send?access_token=xx");        config.setSecret("xxxx"); // call dingtools. sendActionCard("Test Review"."This is a test review message.",config);    }Copy the code

For the caller, just two things, spell Config, and then call the utility class. The utility class can manipulate third parties of different principals by passing in different Config, which is very similar to so-called stateless

conclusion

A Config, an entity package, and a Tools. This is simple for the caller as well as for itself.