전체 페이지뷰

2013년 8월 29일 목요일

Item 3: Enforce the singleton property with a private constructor or an enum type

Making a class a singleton can make it difficult to test its clients

In one approach, the member is a final field:
// Singleton with public final field
    public class Elvis {
        public static final Elvis INSTANCE = new Elvis();
        private Elvis() { ... }
        public void leaveTheBuilding() { ... }
   }

In the second approach to implementing singletons, the public member is a
static factory method:
    // Singleton with static factory
    public class Elvis {
         private static final Elvis INSTANCE = new Elvis();
         private Elvis() { ... }
         public static Elvis getInstance() { return INSTANCE; }
         public void leaveTheBuilding() { ... }
    }

As of release 1.5, there is a third approach to implementing singletons. Simply
make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
     INSTANCE;
     public void leaveTheBuilding() { ... }
}

a single-element enum type is the best way to implement a singleton

댓글 없음:

댓글 쓰기