java 枚举中使用单例模式

假设我们发送消息的方式是配置在文件中或库中,发送前根据配置来决定如何发送消息。

先定义一个消息抽象类

/**
 * 消息抽象类
 */
public abstract class BaseMessage {

    private String content;

    public abstract void send();

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

将发送消息的类型放到枚举中

/**
 * 消息发送枚举
 */
public enum ExecutorSendMsgEnum {
    SMS("sms", new SmsMessage()),
    Email("email", new EmailMessage());

    ExecutorSendMsgEnum(String title, BaseMessage baseMessage) {
        this.title = title;
        this.baseMessage = baseMessage;
    }

    private String title;
    private BaseMessage baseMessage;

    public String getTitle() {
        return title;
    }

    public BaseMessage getBaseMessage() {
        return baseMessage;
    }

    public static ExecutorSendMsgEnum match(String name, ExecutorSendMsgEnum defaultItem) {
        if (name != null) {
            for (ExecutorSendMsgEnum item : ExecutorSendMsgEnum.values()) {
                if (item.getTitle().equals(name)) {
                    return item;
                }
            }
        }
        return defaultItem;
    }
}

发送消息的实现

/**
 * 短信消息
 */
public class SmsMessage extends BaseMessage {
    @Override
    public void send() {
        System.out.println("发送短信:" + getContent());
    }
}

发送消息的实现

/**
 * 邮件消息
 */
public class EmailMessage extends BaseMessage {
    @Override
    public void send() {
        System.out.println("发送邮件:" + getContent());
    }
}

最后测试一下

        if (ExecutorSendMsgEnum.SMS == ExecutorSendMsgEnum.match("sms", null)) {
            BaseMessage baseMessage = ExecutorSendMsgEnum.SMS.getBaseMessage();
            baseMessage.setContent("发送消息喽");
            baseMessage.send();
        }

打印:
发送短信:发送消息喽

posted @ 2022-06-08 18:14  mantishell  阅读(36)  评论(0编辑  收藏  举报