package com.example.kafka.notify;import java.util.ArrayList;import java.util.List;public abstract class Subject { private List
具体主题角色
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
学无止境~~