29 July 2016

Singleton Design Pattern in Java

Singleton Design Pattern
Java 2016
package Demo28;

public class Singleton {
   private static Singleton instance = null;

   private Singleton() {}

   public static synchronized Singleton getInstance() {
      if (instance == null) {
         instance = new Singleton();
      }
      return instance;
   }

   public void connect() {
      //TODO something Làm gì đó.
   }
}

class B {
   public void Test() {
      Singleton s = Singleton.getInstance(); //Phải thông qua getInstance mới được chạy connect
      s.connect();
   }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang