* 싱글턴 패턴
package statictest;
public class TestSingleton {
/**
* @param args
*/
public static void main(String[] args) {
SingletonClass sc1 = SingletonClass.getInstance();
sc1.setNum(100);
SingletonClass sc2 = SingletonClass.getInstance();
System.out.println(sc2.getNum());
SingletonClass2 sc3 = SingletonClass2.getInstance();
sc3.setNum(200);
SingletonClass2 sc4 = SingletonClass2.getInstance();
System.out.println(sc4.getNum());
}
}
----------------------------------
package statictest;
/*싱클톤 패턴
1. 생성자의 접근 제한자를 private
2. private static 변수로 자신의 타입의 변수를 선언
3. public static 메소드를 통해 2번의 static 변수에 할당된 자신 타입의 객체를 return
*/
public class SingletonClass {
private static SingletonClass instance = new SingletonClass();
private int num;
private SingletonClass(){}
public static SingletonClass getInstance(){
return instance;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
------------------------------------
package statictest;
public class SingletonClass2 {
private static SingletonClass2 instance;
private int num;
private SingletonClass2(){}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
//처음 요청이 들어왔을때 객체를 생성하여 객체 생성을 늦추는 방식.
public static SingletonClass2 getInstance() {
if(instance == null){
instance = new SingletonClass2();
}
return instance;
}
}
'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글
this, super키워드 (0) | 2012.07.28 |
---|---|
상속, 생성자 (0) | 2012.07.28 |
static 예 (0) | 2012.07.28 |
staticTest[실습] (0) | 2012.07.28 |
package, import (0) | 2012.07.28 |