Back-end/Java, Kotlin
싱글톤 패턴에 객체 주입받기! (ft.빌더)
philo0407
2021. 3. 7. 02:12
LazyHolder로 작성한 Thread-Safe 싱글톤 패턴이다! + 빌더
이것을 사용하는 이유는 아래 글을 참고!
싱글톤 패턴(Singleton pattern)을 쓰는 이유와 문제점 (tistory.com)
싱글톤 패턴(Singleton pattern)을 쓰는 이유와 문제점
싱글톤 패턴(Singleton Pattern) 싱글톤 패턴 애플리케이션이 시작될 때 어떤 클래스가 최초 한번만 메모리를 할당하고(Static) 그 메모리에 인스턴스를 만들어 사용하는 디자인패턴. 생성자가 여러
jeong-pro.tistory.com
www.daleseo.com/lombok-useful-annotations/
[자바] 알아두면 유용한 Lombok 어노테이션
Engineering Blog by Dale Seo
www.daleseo.com
호출부이다.
public class Caller {
public static void main(String[] args) {
BoardMapper boardMapper = new BoardMapper();
Something s1 = Something.getInstance(boardMapper);
Something s2 = Something.getInstance(boardMapper);
System.out.println(s1);
System.out.println(s2);
Something.testStatic();
s1.testInstance();
}
}
실행 결고과는 아래와 같다.
singleton.Something@123a439b
singleton.Something@123a439b
im the Something of static
im the Something of instance
public class Something {
private static BoardMapper mapper;
private Something() { }
private static class LazyHolder {
public static final Something INSTANCE = new Something();
public final static void setProperty(BoardMapper _mapper) {
mapper = _mapper;
}
}
public static Something getInstance(BoardMapper _mapper) {
LazyHolder.setProperty(_mapper);
return LazyHolder.INSTANCE;
}
public static void testStatic() {
System.out.println("im the Something of static");
}
public void testInstance() {
System.out.println("im the Something of instance");
}
}
class BoardMapper { }
setProperty 빌더 패턴의 메서드 체이닝을 생각해서 return this를 넣어서 하고 싶었지만
싱글톤패턴이랑 엮임 + 역량 부족으로 실패하였다. ㅠㅠ