面试过程中很多面试官如何手写个发布订阅模式下面就是一个简单的demo
//qq实体
public class QqMessage extends Observable {
private static QqMessage qqMessage=null;
public QqMessage() {
}
public static QqMessage getQqMessage(){
if(qqMessage==null){
qqMessage=new QqMessage();
}
return qqMessage;
}
public void publishMessage(String message){
System.out.println("发送的消息"+message);
setChanged();
notifyObservers(message);
}
public class Friend implements Observer {
private String name;
public Friend(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
QqMessage qqMessage = (QqMessage) o;
String message = (String) arg;
System.out.println("==================="+qqMessage);
System.out.println("通知消息"+name+message);
}
public static void main(String[] args) {
QqMessage message = QqMessage.getQqMessage();
Friend teacher=new Friend("cat");
message.addObserver(teacher);
message.publishMessage("小明向qq空间提问了一条消息");
}
网友评论