Tech/Java
싱글톤 패턴(Singleton Pattern)
Dog발자.
2020. 6. 2. 08:35
반응형

- 싱글톤 패턴
- 실글톤 패턴으로 만들어진 Class 는 여러번 생성(인스턴스 화) 하더라도 실제로는 한번만 생성된 Class 패턴을 의미한다.
code (싱글톤 패펀 Class)
public class TestSingleton {
private static TestSingleton instance;
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
private TestSingleton () {
}
public static TestSingleton getInstance () {
if (instance == null) {
instance = new TestSingleton();
}
return instance;
}
}
-
생성자가 private 이기 때문에 외부에서 Class를 생성(인스턴스화) 할 수 없다. ( new TestSingleton() 불가능 )
-
getInstance() 메소드는 static 이기 때문에 Class 생성없이 접근이 가능한다. ( TestSingleton.getInstance )
getInstance() 메소드가 생성없이 접근할 수 있는 이유는 아래 쪽 Static관련 링크에서 확인 해보자
code
public class SingletonMain {
public static void main(String[] arg) {
TestSingleton ts1 = TestSingleton.getInstance();
TestSingleton ts2 = TestSingleton.getInstance();
// 0 0
System.out.println(ts1.getValue());
System.out.println(ts2.getValue());
// 1 1
ts1.setValue(1);
System.out.println(ts1.getValue());
System.out.println(ts2.getValue());
// 2 2
ts1.setValue(2);
System.out.println(ts1.getValue());
System.out.println(ts2.getValue());
System.out.println(ts1.hashCode());
System.out.println(ts2.hashCode());
Singoleton s1 = Singoleton.instance;
Singoleton s2 = Singoleton.instance;
System.out.println(s1.getA());
s1.setA(500);
System.out.println(s1.getA());
System.out.println(s2.getA());
}
}
ts1, ts2는 하나의 TestSingleton 인스턴트를 보고있다. 그렇게 때문에 둘중 어느 setValue() 메소드로 값을 바꾸더라도 같은 값을 보고있기 때문에 ts1, ts2의 getValue() 메소드 값으로 값을 확인하면 같은 것을 볼 수 있다.
반응형