싱글톤 패턴이란?
- 프로그램에서 인스턴스가 단 한 개만 생성되어야 하는 경우 사용하는 디자인 패턴
- static 변수, 메서드를 활용하여 구현 할 수 있음
싱글톤 패턴으로 회사 객체 구현하기
- 생성자는 private으로 선언
private Company() {}
클래스 내부에 유일한 private 인스턴스 생성
private static Company instance = new Company();
- 외부에서 유일한 인스턴스를 참조할 수 있는 public 메서드 제공
public static Company getInstance() {
if( instance == null) {
instance = new Company();
}
return instance;
}
public class CompanyTest {
public static void main(String[] args) {
Company company1 = Company.getInstance();
Company company2 = Company.getInstance();
System.out.println(company1);
System.out.println(company2);
//Calendar calendar = Calendar.getInstance();
}
}
'programming' 카테고리의 다른 글
객체 배열 사용하기 (0) | 2021.06.24 |
---|---|
자료를 순차적으로 한꺼번에 관리하는 방법 - 배열(array) (0) | 2021.06.24 |
static메서드의 구현과 활용, 변수의 유효 범위 (0) | 2021.06.20 |
여러 인스턴스에서 고통으로 사용하는 변수를 선언하자 - static 변수 (0) | 2021.06.20 |
객체 자신을 가리키는 this (0) | 2021.06.16 |
댓글