• 设计模式——行为模式


    //客户端接口

    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());
            
         }
    }

  • 相关阅读:
    排序简介
    排序集锦
    排序图解
    UVA 11809
    uva1588kickdown
    C++中输入输出的重定向
    uva1587BOX
    uva 10340 All in All
    uva 1368 DNA Consensus String
    彻底理解MapReduce shuffle过程原理
  • 原文地址:https://www.cnblogs.com/macro-renzhansheng/p/12568491.html
Copyright © 2020-2023  润新知