싱글톤 패턴(Singleton Pattern)
은 프로그램에서 어떤 클래스의 객체를 딱 하나만 만들고, 그 객체를 어디서든지 사용할 수 있게 하는 방법입니다. 쉽게 말해, "딱 한번만 만들어서 다 같이 쓰자!"라는 공유 자원 개념이다.
클래스 내부에 static 변수를 선언하고 해당 변수에 new를 사용해서 프로그램이 시작되기 전 단 하나의 객체를 생성해서 변수에 저장해 둡니다.
클래스의 생성자를 private으로 만들어서, 외부에서 이 클래스를 new 키워드로 객체를 만들지 못하게 합니다. //방법1
//static 변수를 private으로 하고 객체를 리턴하는 public static A getInstance() 메서드를
//만들어 줍니다. 외부에서 A.getInstance(); 로 해당 객체를 호출
public class Doorman {
private static Doorman doorman = new Doorman();
private Doorman() {}
public static Doorman getInstance() {
return doorman;
//메서드
}
//방법2
//외부에서는 Doorman.instance 로 객체 호출
public class Doorman {
public static Doorman instance = new Doorman();
private Doorman() {}
//메서드
}
Share article