確保物件的唯一性——單例模式 (二)
阿新 • • 發佈:2018-12-21
class Client { public static void main(String args[]) { //建立四個LoadBalancer物件 LoadBalancer balancer1,balancer2,balancer3,balancer4; balancer1 = LoadBalancer.getLoadBalancer(); balancer2 = LoadBalancer.getLoadBalancer(); balancer3 = LoadBalancer.getLoadBalancer(); balancer4 = LoadBalancer.getLoadBalancer(); //判斷伺服器負載均衡器是否相同 if (balancer1 == balancer2 && balancer2 == balancer3 && balancer3 == balancer4) { System.out.println("伺服器負載均衡器具有唯一性!"); } //增加伺服器 balancer1.addServer("Server 1"); balancer1.addServer("Server 2"); balancer1.addServer("Server 3"); balancer1.addServer("Server 4"); //模擬客戶端請求的分發 for (int i = 0; i < 10; i++) { String server = balancer1.getServer(); System.out.println("分發請求至伺服器: " + server); } }}