scene:michael and cavin in char room,they can got common messages from manager.
code:
first we need a manager,
package observer;
import java.util.Observable;
/**
* char room manager.
* @author michael
*/
public class CharRoomManage extends Observable {
private String gonggao;
public String getGonggao() {
return gonggao;
}
public void setGonggao(String gonggao) {
this.gonggao = gonggao;
setChanged();
notifyObservers(gonggao);
}
}
this manager class can create a manager to send common messages.
second we need the observe persons,
package observer;
import java.util.Observable;
import java.util.Observer;
/**
* CharPerson,to create chat Person.
* @author michael
*/
public class ChatPerson implements Observer {
private String gonggao;
private String chatPersonName;
public ChatPerson(String chatPersonName) {
this.chatPersonName=chatPersonName;
}
public void update(Observable o, Object arg) {
if(arg instanceof String){
gonggao=(String)arg;
System.out.println(chatPersonName+"收到站内消息: "+gonggao);
}
}
}
this class can create as many chat room users as we want.
finally we use a main method for test,
package observer;
public class TestMain {
public static void main(String[] args) {
//craete a chat room manage
CharRoomManage manager = new CharRoomManage();
//create two person,those will be observe
ChatPerson mihcael=new ChatPerson("michael");
ChatPerson cavin=new ChatPerson("cavin");
//create relation
manager.addObserver(mihcael);
manager.addObserver(cavin);
//send commons messages
manager.setGonggao("请不要乱发消息");
}
}
run this the result is:
cavin收到站内消息: 请不要乱发消息
michael收到站内消息: 请不要乱发消息