springboot response message message simple single package embodiment and prototype pattern

Directly on the code:

1, the definition of static methods

import com.alibaba.fastjson.JSON;

public class MessageUtils implements Cloneable {
    private static final MessageUtils instance = new MessageUtils();  // 单例模式

    public MessageUtils clone() {
        try {
            return (MessageUtils) super.clone();
        } catch (Exception e) {
            return new MessageUtils();
        }
    }

    // 初始化方法
    public static MessageUtils newMessage() {
        return instance.clone();  // 原型模式
    }

    private String code;
    private boolean success;
    private String message;
    private Object data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static String error510() {
        return fullMessage("510", false, "无此权限", null);
    }

    public static String error508() {
        return fullMessage("508", false, "系统异常,请稍后再试", null);
    }

    public static String error200(String message) {
        return fullMessage("200", false, message, null);
    }

    public static String ok200() {
        return ok200(null);
    }

    public static String ok200(String message) {
        return ok200(message, null);
    }

    public static String ok200(String message, Object data) {
        return fullMessage("200", true, message, data);
    }

    public static String ok200(Object data) {
        return fullMessage("200", true, "OK", data);
    }

    // 完整方法
    public static String fullMessage(String code, boolean success, String message, Object data) {
        MessageUtils msg = instance.clone();
        msg.setCode(code);
        msg.setSuccess(success);
        msg.setMessage(message);
        msg.setData(data);
        return JSON.toJSONString(msg);
    }
}

2, use:

MessageUtils.ok200 return (); 
return MessageUtils.error200 ( "account does not exist"); 
return MessageUtils.ok200 (Object); 
and so on ...

 

Guess you like

Origin www.cnblogs.com/SamNicole1809/p/12610625.html
Recommended