[OOD设计] - Pub Sub Pattern (观察者设计模式)

题目描述 & 链接

Lintcode. Pub-Sub Pattern: 构建一个观察者模型,实现下面问询:1.让用户订阅;2.让用户取消订阅;3.给某频道发送信息,所有订阅该频道的用户都会收到 

题目思路

思路比较简单,可以建立一个HashMap,保存每一个channel对应订阅的用户,然后每一次发送信息就枚举所有订阅用户发送即可,这里需要注意我们可以选择ArrayList来保存用户,但是问题是:1.查重不好处理;2. 删除操作需要O(N)。因此这里使用 HashMap<String, HashSet<Integer>>来存储订阅用户,可以高效查重和删除。

代码如下:

/* Definition of PushNotification
 * class PushNotification {
 *     public static void notify(int user_id, String the_message)
 *  };
 */
public class PubSubPattern {
    HashMap<String, HashSet<Integer>> sub;
    public PubSubPattern(){
    	// Write your code here
        sub = new HashMap<>();
    }
    
    /**
     * @param channel: the channel's name
     * @param user_id: the user who subscribes the channel
     * @return: nothing
     */
    public void subscribe(String channel, int user_id) {
        // Write your code here
        if(!sub.containsKey(channel)) sub.put(channel, new HashSet<>());
        sub.get(channel).add(user_id);
    }

    /**
     * @param channel: the channel's name
     * @param user_id: the user who unsubscribes the channel
     * @return: nothing
     */
    public void unsubscribe(String channel, int user_id) {
        // Write your code here
        if(!sub.containsKey(channel)) return;

        sub.get(channel).remove(user_id);
    }

    /**
     * @param channel: the channel's name
     * @param message: the message need to be delivered to the channel's subscribers
     * @return: nothing
     */
    public void publish(String channel, String message) {
        // Write your code here
        if(!sub.containsKey(channel)) return;
        for(int i: sub.get(channel)) {
            PushNotification.notify(i, message);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值