观察者模式通常由两个对象组成:观察者和被观察者。当被观察者状态发生改变时,它会通知所有的观察者对象,使他们能够及时做出响应,所以也被称作“发布-订阅模式”。
示例代码
/**
* @author Created by njy on 2023/6/1
* 报纸接口,即被观察者接口
*/
public interface Newspaper {
/**
* 添加订阅者
* @param subscriber
*/
void addSubscriber(Subscriber subscriber);
/**
* 移除订阅者
* @param subscriber
*/
void removeSubscriber(Subscriber subscriber);
/**
* 通知订阅者
* @param message
*/
void notifySubscribers(String message);
}
import java.util.ArrayList;
import java.util.List;
/**
* @author Created by njy on 2023/6/1
* 报纸实现类
*/
public class NewspaperImpl implements Newspaper{
//订阅者集合
List<Subscriber> subscribers = new ArrayList<>();
//添加订阅者
@Override
public void addSubscriber(Subscriber subscriber) {
subscribers.add(subscriber);
}
//移除订阅者
@Override
public void removeSubscriber(Subscriber subscriber) {
subscribers.remove(subscriber);
}
//通知订阅者
@Override
public void notifySubscribers(String message) {
for (Subscriber s : subscribers) {
s.update(message);
}
}
}
/**
* @author Created by njy on 2023/6/1
* 订阅者(即观察者)接口
*/
public interface Subscriber {
void update(String message);
}
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author Created by njy on 2023/6/1
* 具体订阅者
*/
@Data
@AllArgsConstructor
public class SubscriberImpl implements Subscriber{
private String name;
@Override
public void update(String message) {
System.out.println(name + "---接到消息: " + message);
}
}
@SpringBootTest
public class TestObserver {
@Test
void testObserver(){
Newspaper newspaper = new NewspaperImpl();
Subscriber li = new SubscriberImpl("李老头");
Subscriber wang = new SubscriberImpl("王奶奶");
//李老头和王奶奶订阅了报纸
newspaper.addSubscriber(li);
newspaper.addSubscriber(wang);
//报纸到了,通知订阅者
newspaper.notifySubscribers("今天的报纸到了!!!");
//李老头取消订阅了,移除
newspaper.removeSubscriber(li);
newspaper.notifySubscribers("明天的报纸还是这个点到!!!");
}
}