设计模式——策略模式

策略模式

介绍

  针对一组算法,将每一个算法封装到具有共同接口的独立类中,也就是给出一个接口或者抽象类A(类似于规范),其他类B、C、D实现或者继承A进行具体算法或行为的描述。

示例

  一个平台的通知消息的推送功能,可以通过策略模式进行操作。

通知接口

public interface MessageNotice {

    /**
     * 通知类型是否支持
     *
     * @param type 0:短信 1:邮件
     * @return
     */
    boolean support(int type);

    /**
     * 通知操作
     *
     * @param user
     * @param content
     */
    void notify(User user, String content);

}

短信通知实现

@Component
public class SMSMessageNotice implements MessageNotice {
    @Override
    public boolean support(int type) {
        return type == 0;
    }

    @Override
    public void notify(User user, String content) {
        //调用短信通知的api,通知对应用户发送短信
    }
}

邮件通知实现

@Component
public class EmailMessageNotice implements MessageNotice {
    @Override
    public boolean support(int type) {
        return type == 1;
    }

    @Override
    public void notify(User user, String content) {
        //调用短信通知的api,通知对应用户发送邮件
    }
}

消息通知调用入口

@Resource
private List<MessageNotice> messageNoticeList;

//通知入口
public void notifyMessage(User user, String content, int notifyType) {
    for (MessageNotice messageNotice : messageNoticeList) {
        if (messageNotice.support(notifyType)) {
        //根据不同的notifyType进入不同的通知操作行为中
            messageNotice.notify(user, content);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容