釋出訂閱模式簡單實現
阿新 • • 發佈:2022-04-02
https://www.cnblogs.com/Andrew520/p/11116516.html
1 package com.sunny.core.sunnycore.ssm.publish; 2 3 import com.sunny.core.sunnycore.ssm.subscriber.Subscriber; 4 import org.springframework.stereotype.Service; 5 6 /** 7 * @Description: TODO 8 * @Author Lg 9 * @Date 2022/4/2 10 */ 11 @Service 12 publicinterface PublishService { 13 //註冊 14 void register(Subscriber subscriber); 15 //刪除 16 void remove(Subscriber subscriber); 17 //通知 18 void notifyObserver(); 19 }
1 package com.sunny.core.sunnycore.ssm.publish; 2 3 import com.sunny.core.sunnycore.ssm.subscriber.Subscriber; 4import org.springframework.util.ObjectUtils; 5 6 import java.util.ArrayList; 7 import java.util.List; 8 import java.util.Observer; 9 10 /** 11 * @Description: TODO 12 * @Author Lg 13 * @Date 2022/4/2 14 */ 15 public class PublishServiceImpl implements PublishService{ 16 17 //訂閱者集合 18 privateList<Subscriber> userList = new ArrayList<>(); 19 //訊息 20 private String message; 21 @Override 22 public void register(Subscriber subscriber) { 23 userList.add(subscriber); 24 } 25 26 @Override 27 public void remove(Subscriber subscriber) { 28 if(!ObjectUtils.isEmpty(subscriber)&&userList.size()>0){ 29 userList.remove(subscriber); 30 } 31 } 32 33 @Override 34 public void notifyObserver() { 35 userList.forEach(e->{ 36 e.getMessage(message); 37 }); 38 } 39 40 public void setMessage(String message){ 41 this.message = message; 42 notifyObserver(); 43 } 44 }
1 package com.sunny.core.sunnycore.ssm.subscriber; 2 3 import org.springframework.stereotype.Service; 4 5 /** 6 * @Description: TODO 7 * @Author Lg 8 * @Date 2022/4/2 9 */ 10 @Service 11 public interface Subscriber { 12 //得到訊息 13 void getMessage(String message); 14 }
1 package com.sunny.core.sunnycore.ssm.subscriber; 2 3 /** 4 * @Description: TODO 5 * @Author Lg 6 * @Date 2022/4/2 7 */ 8 public class SubscriberImpl implements Subscriber{ 9 10 //訂閱者名稱 11 private String name; 12 //訊息 13 private String message; 14 15 public SubscriberImpl(String name) { 16 this.name = name; 17 } 18 @Override 19 public void getMessage(String message) { 20 this.message = message; 21 read(); 22 } 23 24 private void read() { 25 System.out.println(name + ":" + "收到訊息內為:" + message); 26 } 27 }