package 싱글톤패턴;
public class SingletonTest {
// private static SingletonTest instance = new SingletonTest(); // 인스턴스 객체화
// LazyHolder 이용 동기화
private static class LazyHolder {
static final SingletonTest INSTANCE = new SingletonTest();
}
private String name;
private int age;
private SingletonTest() { // 이걸 사용함으로 다른 클래스에서 생성불가
}
// ----synchronized 이용 동기화----
// public static SingletonTest getInstance() {
// if (instance == null) {
// synchronized (SingletonTest.class) {
// if (instance == null) {
// instance = new SingletonTest();
// }
// }
// }
// return instance;
// }
public static SingletonTest getInstance() {
return LazyHolder.INSTANCE;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
----------------------------------------------
package 싱글톤패턴;
public class SingletonExample {
public static void main(String[] args) {
//메서드체이닝
System.out.println(SingletonTest.getInstance().getAge()); // 0
System.out.println(SingletonTest.getInstance().getName()); // null
//변수 활용
SingletonTest user1 = SingletonTest.getInstance();
SingletonTest user2 = SingletonTest.getInstance();
System.out.println(user1); // 싱글톤패턴.SingletonTest@15db9742
System.out.println(user1.getAge()); // 0
System.out.println(user1.getName()); // null
System.out.println("");
user1.setAge(10);
user1.setName("A");
System.out.println(user1.getAge()); // 10
System.out.println(user1.getName()); // A
System.out.println("----------------");
user2.setAge(20);
user2.setName("B");
System.out.println(user2.getAge()); // 20
System.out.println(user2.getName()); // B
}
}
'Code 예제' 카테고리의 다른 글
DataTables Ajax 배열 txt파일 불러오는 기본예제해보기 (0) | 2019.10.25 |
---|---|
빌더 패턴 (0) | 2018.12.26 |
팩토리 패턴 예제 (0) | 2018.12.17 |
더블링크드 리스트 예제 (0) | 2018.12.17 |
피보나치 수열 시간복잡도 개선 (0) | 2018.12.17 |