티스토리 뷰
1. Singleton
- statickeyword에 포함된다.
- 객체가 여러 개 만들어져서 heap에 있는 하나의 값에 모두 접근하고 있다면,
객체를 하나만 만들어서 주소값만 나눠주자!!!
package com.ohgiraffers.section06.singleton;
public class Application {
public static void main(String[] args) {
/* 수업목표. 싱글톤 패턴에 대해 이해하고 이를 구현할 수 있다. */
/* 필기.
* singleton pattern이란?
* 애플리케이션이 시작되고 난 후 어떤 클래스가 최초 한번만 메모리에 할당(객체)되고
* 그 메모리에 인스턴스가 단 하나만 생성되어 공유되게 하는 것을 싱글톤 패턴이라고 한다.
* (메모리 및 리소스 낭비 방지 목적)
*
* 필기.
* 장점
* 1. 첫 번째 이용 시에는 인스턴스를 생성해야 하므로 속도 차이가 나지 않지만
* 두 번째 이용 시에는 인스턴스 생성 시간 없이 바로 사용할 수 있다.(재사용)
* 2. 인스턴스가 절대적으로 한 개만 추구하는 것을 보증할 수 있다.
* 단점
* 1. 싱글톤 인스턴스가 너무 많은 일을 하거나 많은 데이터를 공유하면 결합도가 높아진다.
* 2. 동시성 문제를 고려해서 설계해야 하기 때문에 난이도가 높다.
*
* 필기.
* 싱글톤 구현 방법
* 1. 이른 초기화(Eager Initialization)
* 2. 늦은 초기화(Lazy Initialization)
* */
EagerSingleton eager1 = EagerSingleton.getInstance(); // 프로그램을 켜자마자 생성된 객체의 주소
EagerSingleton eager2 = EagerSingleton.getInstance();
// EagerSingleton eager3 = new EagerSingleton(); // 생성자가 private이므로
System.out.println("eager1의 주소: " + System.identityHashCode(eager1));
System.out.println("eager2의 주소: " + System.identityHashCode(eager2));
LazySingleton lazy1 = LazySingleton.getInstance(); // 이 시점에 객체가 생성됨
LazySingleton lazy2 = LazySingleton.getInstance();
System.out.println("lazy1의 주소: " + System.identityHashCode(lazy1));
System.out.println("lazy2의 주소: " + System.identityHashCode(lazy2));
}
}
// 실행 결과
eager1의 주소: 112810359
eager2의 주소: 112810359
lazy1의 주소: 1309552426
lazy2의 주소: 1309552426
package com.ohgiraffers.section06.singleton;
public class EagerSingleton {
// 메모리 구조 생각하면서 이해해보자!!
private static EagerSingleton eager = new EagerSingleton();
private EagerSingleton() { // 얘를 활용하는 거다!, private까지 작성해야 완벽한 singleton
}
public static EagerSingleton getInstance() {
return eager;
}
}
package com.ohgiraffers.section06.singleton;
public class LazySingleton {
private static LazySingleton lazy;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (lazy == null) {
lazy = new LazySingleton();
}
return lazy;
}
}
2. StaticKeyword
package com.ohgiraffers.section06.statickeyword;
public class Application {
public static void main(String[] args) {
/* 수업목표. static 키워드에 대해 이해할 수 있다. */
/* 필기.
* static
* : 프로그램이 실행될 때 정적 메모리 영역(static 영역 또는 클래스 영역)에 할당하는 키워드이다.
* 여러 인스턴스가 공유해서 사용할 목적의 공간이다.
* 대표적인 예로 싱글톤(singleton) 객체가 있다.
* */
// 메모리 구조 그려보면서 이해해보자!
StaticTest st1 = new StaticTest();
/* 설명. 현재 두 필드가 가지고 있는 값 확인 */
System.out.println("non-static field: " + st1.getNonStaticCount());
System.out.println("static field: " + StaticTest.getStaticCount());
/* 설명. 각 필드 값들을 하나씩 증가 */
st1.increaseNonStaticCount();
StaticTest.increaseStaticCount();
/* 설명. 두 필드 값 확인 */
System.out.println("non-static field: " + st1.getNonStaticCount());
System.out.println("static field: " + StaticTest.getStaticCount());
/* 설명. 새로운 객체 생성 */
StaticTest st2 = new StaticTest();
System.out.println("non-static field: " + st2.getNonStaticCount());
System.out.println("static field: " + StaticTest.getStaticCount());
}
}
// 실행 결과
non-static field: 0
static field: 0
non-static field: 1
static field: 1
non-static field: 0
static field: 1
package com.ohgiraffers.section06.statickeyword;
public class StaticTest {
private int nonStaticCount;
private static int staticCount; // static 메소드로!
public StaticTest() {
}
public int getNonStaticCount() {
return nonStaticCount;
}
public static int getStaticCount() {
return staticCount;
}
public void increaseNonStaticCount() {
this.nonStaticCount++;
}
public static void increaseStaticCount() {
staticCount++;
}
}
'한화시스템 > 백엔드' 카테고리의 다른 글
[BE] JAVA_클래스와 객체_객체 배열 (0) | 2024.07.16 |
---|---|
[BE] JAVA_클래스와 객체_초기화 블럭 (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_오버로딩 & 매개변수 (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_생성자 (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_추상화 (0) | 2024.07.16 |