springboot 响应消息 message简单封装 单例和原型模式

直接上代码:

1、定义静态方法

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、使用方法:

return MessageUtils.ok200();
return MessageUtils.error200("账号不存在");
return MessageUtils.ok200(Object);
等等...
原文地址:https://www.cnblogs.com/SamNicole1809/p/12610625.html