//客户端接口
public interface UpdatableClient {
public void update(String msg);
}
//服务端接口
public interface Serverable {
public void registObserver(Client client);
public void removeObserver(Client client);
public void notifyObserver(String msg);
}//客户实现类
public class Client implements UpdatableClient{
private String name;
public Client(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void update(String msg) {
// TODO Auto-generated method stub
System.out.println("client_"+name+"接收到信息:"+msg);
}}
//服务器实现类
import java.util.ArrayList;
import java.util.List;public class Server implements Serverable{
private String name;
private List<Client> regisTable;
public Server() {
regisTable = new ArrayList<Client>();
name = "默认服务器-administrator";
}
public Server(String name, List<Client> regisTable) {
super();
this.name = name;
this.regisTable = regisTable;
}
@Override
public void registObserver(Client client) {
// TODO Auto-generated method stub
regisTable.add(client);
}
@Override
public void removeObserver(Client client) {
// TODO Auto-generated method stub
regisTable.remove(client);
}
@Override
public void notifyObserver(String msg) {
// TODO Auto-generated method stub
for (Client client : regisTable) {
client.update(msg);
}
}
}
//测试
public class Demo {
public static void main(String[] args) {
Server server = new Server();
Client clientA = new Client("java");
server.registObserver(clientA);
Client clientB = new Client("SQL");
server.registObserver(clientB);
Client clientC = new Client("C++");
server.registObserver(clientC);
server.notifyObserver("hello,everyone");
server.removeObserver(clientB);
server.notifyObserver("hello,remove client_"+clientB.getName());
}
}