欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

设计模式-观察者模式

时间:2023-04-22

package com.example.kafka.notify;import java.util.ArrayList;import java.util.List;public abstract class Subject { private List list = new ArrayList<>(); public void addObserver(Observer obj){ list.add(obj); } public void deleteObserver(Observer obj){ list.remove(obj); } public void notifyAllObserver(){ for (Observer obj:list) { obj.update(this); } } }

具体主题角色

package com.example.kafka.notify;public class GameSubject extends Subject{ private String name; private String content; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public GameSubject(String name, String content) { super(); this.name = name; this.content = content; } public void sendSubject(GameSubject sub){ sub.notifyAllObserver(); }}

抽象观察者

package com.example.kafka.notify;public interface Observer { public void update(Subject sub);}

 具体观察者角色

package com.example.kafka.notify;import ch.qos.logback.core.net.SyslogOutputStream;public class GamePlay implements Observer{ @Override public void update(Subject sub) { GameSubject subject = (GameSubject) sub; String content = subject.getContent(); if (content != null){ content = content.toLowerCase(); } if(content.contains("pc")){ System.out.println("PC玩家: 我这个主题非常感兴趣!"); } else { System.out.println("我对这个主题不感兴趣!"); } System.out.println("本次游行主题发布者:"+subject.getName()); }}

测试

public static void main(String[] args) { String name = "jack"; String content="英雄联盟手游版+PC版"; GameSubject gameSubject = new GameSubject(name, content); Observer observer = new GamePlay(); gameSubject.addObserver(observer); gameSubject.sendSubject(gameSubject);}

执行结果

PC玩家: 我这个主题非常感兴趣!本次游行主题发布者:jack

学无止境~~

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。