Home > Java > javaTutorial > How does java define the Union class to realize the coexistence of data bodies?

How does java define the Union class to realize the coexistence of data bodies?

王林
Release: 2023-05-14 15:34:06
forward
2184 people have browsed it

Define the Union class to realize the coexistence of data bodies

In C/C language, union, also known as union, is a data structure similar to structure (struct). Union (union), like structure (struct), can contain many data types and variables. The difference between the two is as follows:

  1. All variables in the structure (struct) "coexist" ", all variables are effective at the same time, and each variable occupies a different memory space;

  2. In a union, each variable is "mutually exclusive", and only one variable is effective at the same time. , all variables occupy the same memory space.

When multiple data need to share memory or only one of multiple data needs to be taken at a time, a union can be used.

In the Java language, there is no concept of union and structure (struct), only the concept of class. As we all know, structures can be implemented using classes. In fact, unions can also be implemented using classes. However, this class does not have the function of "multiple data need to share memory", but only the function of "only one of multiple data needs to be taken at a time".

Here, take the customer message of WeChat protocol as an example. Based on my many years of experience in interface protocol encapsulation, there are mainly two implementation methods.

1. Use function method to implement Union

Union class implementation:

/** 客户消息类 */@ToStringpublic class CustomerMessage {    /** 属性相关 */
    /** 消息类型 */
    private String msgType;    /** 目标用户 */
    private String toUser;    /** 共用体相关 */
    /** 新闻内容 */
    private News news;
    ...    /** 常量相关 */
    /** 新闻消息 */
    public static final String MSG_TYPE_NEWS = "news";
    ...    /** 构造函数 */
    public CustomerMessage() {}    /** 构造函数 */
    public CustomerMessage(String toUser) {        this.toUser = toUser;
    }    /** 构造函数 */
    public CustomerMessage(String toUser, News news) {        this.toUser = toUser;        this.msgType = MSG_TYPE_NEWS;        this.news = news;
    }    /** 清除消息内容 */
    private void removeMsgContent() {        // 检查消息类型
        if (Objects.isNull(msgType)) {            return;
        }        // 清除消息内容
        if (MSG_TYPE_NEWS.equals(msgType)) {
            news = null;
        } else if (...) {
            ...
        }
        msgType = null;
    }    /** 检查消息类型 */
    private void checkMsgType(String msgType) {        // 检查消息类型
        if (Objects.isNull(msgType)) {            throw new IllegalArgumentException("消息类型为空");
        }        // 比较消息类型
        if (!Objects.equals(msgType, this.msgType)) {            throw new IllegalArgumentException("消息类型不匹配");
        }
    }    /** 设置消息类型函数 */
    public void setMsgType(String msgType) {        // 清除消息内容
        removeMsgContent();        // 检查消息类型
        if (Objects.isNull(msgType)) {            throw new IllegalArgumentException("消息类型为空");
        }        // 赋值消息内容
        this.msgType = msgType;        if (MSG_TYPE_NEWS.equals(msgType)) {
            news = new News();
        } else if (...) {
            ...
        } else {            throw new IllegalArgumentException("消息类型不支持");
        }
    }    /** 获取消息类型 */
    public String getMsgType() {        // 检查消息类型
        if (Objects.isNull(msgType)) {            throw new IllegalArgumentException("消息类型无效");
        }        // 返回消息类型
        return this.msgType;
    }    /** 设置新闻 */
    public void setNews(News news) {        // 清除消息内容
        removeMsgContent();        // 赋值消息内容
        this.msgType = MSG_TYPE_NEWS;        this.news = news;
    }    /** 获取新闻 */
    public News getNews() {        // 检查消息类型
        checkMsgType(MSG_TYPE_NEWS);        // 返回消息内容
        return this.news;
    }
    
    ...
}
Copy after login

Union class usage:

String accessToken = ...;
String toUser = ...;
List<Article> articleList = ...;
News news = new News(articleList);
CustomerMessage customerMessage = new CustomerMessage(toUser, news);
wechatApi.sendCustomerMessage(accessToken, customerMessage);
Copy after login

Main advantages and disadvantages:

  • Advantages: Closer to the union of C/C language;

  • Disadvantages: The implementation logic is more complex and there are many parameter type verifications.

2. Use inheritance to implement Union

Union class implementation:

/** 客户消息类 */@Getter@Setter@ToStringpublic abstract class CustomerMessage {    /** 属性相关 */
    /** 消息类型 */
    private String msgType;    /** 目标用户 */
    private String toUser;    /** 常量相关 */
    /** 新闻消息 */
    public static final String MSG_TYPE_NEWS = "news";
    ...    /** 构造函数 */
    public CustomerMessage(String msgType) {        this.msgType = msgType;
    }    /** 构造函数 */
    public CustomerMessage(String msgType, String toUser) {        this.msgType = msgType;        this.toUser = toUser;
    }
}/** 新闻客户消息类 */@Getter@Setter@ToString(callSuper = true)public class NewsCustomerMessage extends CustomerMessage {    /** 属性相关 */
    /** 新闻内容 */
    private News news;    /** 构造函数 */
    public NewsCustomerMessage() {        super(MSG_TYPE_NEWS);
    }    /** 构造函数 */
    public NewsCustomerMessage(String toUser, News news) {        super(MSG_TYPE_NEWS, toUser);        this.news = news;
    }
}
Copy after login

Union class usage:

String accessToken = ...;
String toUser = ...;
List<Article> articleList = ...;
News news = new News(articleList);
CustomerMessage customerMessage = new NewsCustomerMessage(toUser, news);
wechatApi.sendCustomerMessage(accessToken, customerMessage);
Copy after login

Main advantages and disadvantages :

  • Advantages: Use virtual base classes and subclasses for splitting, and the concepts of each subclass object are clear;

  • Disadvantages: Unlike C /The union of C language is very different, but the functions are generally the same.

In C/C language, the union does not include the current data type of the union. However, the Java union implemented above already contains the data type corresponding to the union. Therefore, strictly speaking, Java union is not a real union, but a class with the function of "only taking one of multiple data at a time".

The above is the detailed content of How does java define the Union class to realize the coexistence of data bodies?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template