객체 지향 프로그래밍에서 Java 싱글톤 클래스는 한 번에 하나의 객체(클래스의 인스턴스)만 가질 수 있는 클래스입니다. 처음 이후 Java Singleton 클래스를 인스턴스화하려고 하면 새 변수도 생성된 첫 번째 인스턴스를 가리킵니다. 따라서 인스턴스를 통해 클래스 내부의 변수를 수정하면 생성된 단일 인스턴스의 변수에 영향을 미치고 정의된 해당 클래스 유형의 변수를 통해 해당 변수에 액세스하면 표시됩니다.
싱글톤 클래스를 디자인하는 동안 클래스를 싱글톤 클래스로 정의할 때 다음 핵심 사항을 기억하세요.
- 생성자를 비공개로 만듭니다.
- 이 싱글톤 클래스의 반환 유형 개체가 있는 정적 메서드를 작성합니다. 여기서는 지연 초기화 개념을 사용하여 이 정적 메서드를 작성합니다.
싱글톤 클래스의 목적
Java Singleton 클래스의 주요 목적은 객체 생성 수를 하나로 제한하는 것입니다. 이를 통해 소켓이나 데이터베이스 연결과 같은 리소스에 대한 액세스 제어가 보장되는 경우가 많습니다.
싱글톤 클래스를 사용하면 인스턴스 생성이 제한되므로 메모리 공간 낭비가 발생하지 않습니다. 객체 생성은 새로운 요청이 이루어질 때마다 생성되는 것이 아니라 한 번만 발생합니다.
요구 사항에 따라 이 단일 개체를 반복적으로 사용할 수 있습니다. 이것이 바로 멀티 스레드 및 데이터베이스 애플리케이션이 캐싱, 로깅, 스레드 풀링, 구성 설정 등을 위해 Java의 싱글턴 패턴을 주로 사용하는 이유입니다.
예를 들어 라이센스가 있고 데이터베이스 연결이 하나만 있거나 JDBC 드라이버가 멀티스레딩을 허용하지 않는다고 가정하면 Singleton 클래스가 등장하여 한 번에 하나의 연결만 허용되도록 합니다. 또는 단일 스레드가 연결에 액세스할 수 있습니다.
Java에서 싱글톤 클래스를 디자인/생성하는 방법은 무엇입니까?
싱글톤 클래스를 생성하려면 다음 단계를 따라야 합니다.
1. 클래스의 인스턴스가 하나만 존재하는지 확인하십시오.
2. 다음을 통해 해당 인스턴스에 대한 전역 액세스를 제공합니다.
- 클래스의 모든 생성자를 비공개로 선언합니다.
- 인스턴스에 대한 참조를 반환하는 정적 메서드를 제공합니다. 지연 초기화 개념은 정적 메서드를 작성하는 데 사용됩니다.
- 인스턴스는 개인 정적 변수로 저장됩니다.
싱글톤 클래스의 예는 다음과 같습니다. 런타임 클래스, 액션 서블릿, 서비스 로케이터 . 개인 생성자 및 팩토리 메서드도 싱글톤 클래스의 예입니다.
일반 클래스와 싱글톤 클래스의 차이점
클래스의 객체를 인스턴스화하는 과정에서 싱글톤 클래스를 일반적인 클래스와 구별할 수 있습니다. 일반 클래스를 인스턴스화하려면 Java 생성자를 사용합니다. 반면에 싱글톤 클래스를 인스턴스화하려면 getInstance() 메서드를 사용합니다.
다른 차이점은 일반 클래스는 애플리케이션의 수명 주기가 끝나면 사라지는 반면, 싱글톤 클래스는 애플리케이션이 완료되어도 소멸되지 않는다는 것입니다.
싱글톤 클래스 패턴의 형태
싱글톤 디자인 패턴에는 두 가지 형태가 있습니다.
- 초기 인스턴스화: 개체 생성은 로드 시 발생합니다.
- 지연 인스턴스화: 요구 사항에 따라 개체 생성이 수행됩니다.
구현: 싱글톤 클래스가 Java의 일반 클래스와 어떻게 다른지 간략하게 살펴보겠습니다. 여기서 차이점은 인스턴스화 측면에서 일반 클래스에서는 생성자를 사용하는 반면, 싱글톤 클래스에서는 생성자를 사용합니다. getInstance() 메서드 아래에 설명된 것처럼 예제 1에서 살펴보겠습니다. 일반적으로 혼동을 피하기 위해 아래 예제 2에 설명된 이 메서드를 정의하는 동안 클래스 이름을 메서드 이름으로 사용할 수도 있습니다.
예시 1:
자바
// Java program implementing Singleton class> // with using getInstance() method> // Class 1> // Helper class> class> Singleton {> >// Static variable reference of single_instance> >// of type Singleton> >private> static> Singleton single_instance =>null>;> >// Declaring a variable of type String> >public> String s;> >// Constructor> >// Here we will be creating private constructor> >// restricted to this class itself> >private> Singleton()> >{> >s =>'Hello I am a string part of Singleton class'>;> >}> >// Static method> >// Static method to create instance of Singleton class> >public> static> synchronized> Singleton getInstance()> >{> >if> (single_instance ==>null>)> >single_instance =>new> Singleton();> >return> single_instance;> >}> }> // Class 2> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Instantiating Singleton class with variable x> >Singleton x = Singleton.getInstance();> >// Instantiating Singleton class with variable y> >Singleton y = Singleton.getInstance();> >// Instantiating Singleton class with variable z> >Singleton z = Singleton.getInstance();> >// Printing the hash code for above variable as> >// declared> >System.out.println(>'Hashcode of x is '> >+ x.hashCode());> >System.out.println(>'Hashcode of y is '> >+ y.hashCode());> >System.out.println(>'Hashcode of z is '> >+ z.hashCode());> >// Condition check> >if> (x == y && y == z) {> >// Print statement> >System.out.println(> >'Three objects point to the same memory location on the heap i.e, to the same object'>);> >}> >else> {> >// Print statement> >System.out.println(> >'Three objects DO NOT point to the same memory location on the heap'>);> >}> >}> }> |
>
>산출
Hashcode of x is 558638686 Hashcode of y is 558638686 Hashcode of z is 558638686 Three objects point to the same memory location on the heap i.e, to the same object>
출력 설명:

싱글톤 클래스에서 처음 호출할 때 getInstance() 메서드 , Single_instance라는 이름의 클래스 객체를 생성하고 이를 변수에 반환합니다. Single_instance는 정적이므로 null에서 일부 개체로 변경됩니다. 다음에 Single_instance가 null이 아니기 때문에 getInstance() 메서드를 호출하려고 하면 Singleton 클래스를 다시 인스턴스화하는 대신 변수에 반환됩니다. 이 부분은 if 조건에 의해 수행됩니다.
메인 클래스에서는 정적 클래스를 호출하여 x, y, z 3개 객체로 싱글톤 클래스를 인스턴스화합니다. 메소드 getInstance() . 그러나 실제로는 객체 x가 생성된 후 다이어그램에 표시된 대로 변수 y와 z가 객체 x를 가리킵니다. 따라서 객체 x의 변수를 변경하면 객체 y와 z의 변수에 액세스할 때 반영됩니다. 또한 객체 z의 변수를 변경하면 객체 x 및 y의 변수에 액세스할 때 반영됩니다.
이제 예제 1의 모든 측면을 다루고 동일하게 구현했습니다. 이제 클래스 이름과 같은 메서드 이름을 사용하여 Singleton 클래스를 구현하겠습니다.
b+ 트리
예시 2:
자바
// Java program implementing Singleton class> // with method name as that of class> // Class 1> // Helper class> class> Singleton {> >// Static variable single_instance of type Singleton> >private> static> Singleton single_instance =>null>;> >// Declaring a variable of type String> >public> String s;> >// Constructor of this class> >// Here private constructor is used to> >// restricted to this class itself> >private> Singleton()> >{> >s =>'Hello I am a string part of Singleton class'>;> >}> >// Method> >// Static method to create instance of Singleton class> >public> static> Singleton Singleton()> >{> >// To ensure only one instance is created> >if> (single_instance ==>null>) {> >single_instance =>new> Singleton();> >}> >return> single_instance;> >}> }> // Class 2> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Instantiating Singleton class with variable x> >Singleton x = Singleton.Singleton();> >// Instantiating Singleton class with variable y> >Singleton y = Singleton.Singleton();> >// instantiating Singleton class with variable z> >Singleton z = Singleton.Singleton();> >// Now changing variable of instance x> >// via toUpperCase() method> >x.s = (x.s).toUpperCase();> >// Print and display commands> >System.out.println(>'String from x is '> + x.s);> >System.out.println(>'String from y is '> + y.s);> >System.out.println(>'String from z is '> + z.s);> >System.out.println(>'
'>);> >// Now again changing variable of instance z> >z.s = (z.s).toLowerCase();> >System.out.println(>'String from x is '> + x.s);> >System.out.println(>'String from y is '> + y.s);> >System.out.println(>'String from z is '> + z.s);> >}> }> |
>
>산출
String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class>
설명: 싱글톤 클래스에서는 Singleton() 메서드를 처음 호출하면 Single_instance라는 이름의 Singleton 클래스 객체가 생성되어 변수에 반환됩니다. Single_instance는 정적이므로 null에서 일부 개체로 변경됩니다. 다음에 Singleton() 메서드를 호출하려고 하면, Single_instance가 null이 아니기 때문에 Singleton 클래스를 다시 인스턴스화하는 대신 변수에 반환됩니다.
추가 읽기: Java 디자인 패턴 튜토리얼