티스토리 뷰
우리집엔 에어컨에 사용하는 리모컨이 여러대 있다.
거실용 리모컨과 각방의 리모컨은 서로의 공유하며 사용이 가능하다.
이를 토대로 SingleTone 패턴을 생각해보자
public class RemoteControl {
//단 1개만 존재해야하는 객체의 인스턴스이므로 static으로 설정
private static RemoteControl remoteControl;
int temp;
//private 기본생성자를 사용하여 외부에서의 새로운 리모컨 객체가 만들어지는것을 막아야한다.
private RemoteControl() {
//기본 온도 설정값
temp = 20;
}
//오로지 getInstance만을 이용해 객체를 생성할 수 있다.
public static RemoteControl getInstance() {
if (remoteControl == null) {
remoteControl = new RemoteControl();
}
return remoteControl;
}
//온도 설정용 getter,setter
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
}
온도를 구현해본 메인클래스
public class Main {
public static void main(String[] args) {
//거실리모컨
RemoteControl livingRoom = RemoteControl.getInstance();
//내방리모컨
RemoteControl myRoom = RemoteControl.getInstance();
if (livingRoom == myRoom) {
System.out.println("같은 동작");
}
//같은 에어컨인지 확인
System.out.println(livingRoom.getTemp());
System.out.println(myRoom.getTemp());
System.out.println("------------------------");
livingRoom.setTemp(18);
System.out.println("거실리모컨 온도변경 18도");
System.out.println("거실 리모컨 온도 확인 : " + livingRoom.getTemp());
System.out.println("내방 리모컨 온도 확인 : " + myRoom.getTemp());
System.out.println("------------------------");
myRoom.setTemp(22);
System.out.println("내방 리모컨 온도변경 22도");
System.out.println("거실 리모컨 온도 확인 : " + livingRoom.getTemp());
System.out.println("내방 리모컨 온도 확인 : " + myRoom.getTemp());
}
}
하나의 에어컨을 조절할때 2개의 리모컨 설정이 공유되는것을 확인했다.
이해를 하기위해 리모컨이라는 개념을 도입했지만 결국 결론은
객체의 인스턴스를 한개만 생성하도록 만드는 패턴
이 된다.
실제로 사용하는 부분은
- Spring에서 Bean을 관리할때
- TCP 소켓통신을 할때 서버와의 connect
물론 다양한 예가 있지만 가장 중요한 사용처는 이렇게 되지 않을까 싶다.
스프링은 '스프링 컨테이너'에서 객체 인스턴스를 싱글톤으로 관리한다고 한다.
그렇기에 내가 만약 Service에서 Repository 객체를 호출할때
매번 새로운 Repository를 new Repository()로 주입하지않고
private final 혹은 @Autowired 를 사용해 호출하면
동일한 하나의 Repository를 호출해 사용할 수 있는 것이 아닐까 라는게 나의 생각이다.
'Backend > SpringBoot' 카테고리의 다른 글
SpringBoot 다중 파일 업로드 구현 (0) | 2023.04.08 |
---|---|
DTO, VO and Entity... (0) | 2023.01.26 |
양방향맵핑과 'mappedBy' (0) | 2022.12.30 |
ModelMapper Strategies(전략)이란 (0) | 2022.12.28 |
Ajax 와 Json, 그리고 Rest방식 (1) | 2022.12.26 |
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
- 토스페이먼츠
- CompositionAPI
- 함께모으기
- for
- JWT
- 한권으로끝내기리눅스마스터2급
- Vue.js3
- pinia
- mybatis구현
- script setup
- 프로그래머스
- LEVEL2
- 맥 error
- java 플레이그라운드
- 정수형으로 변환
- 객체지향의 사실과 오해
- 다음 큰 숫자
- 타임리프
- 스프링부트
- springboot
- 짝지어제거하기
- vue.js
- 책리뷰
- 객체지향
- 객체 지도
- SpringSecurity
- it책 리뷰
- vuex
- 알고리즘
- 리눅스마스터2급
- Total
- Today
- Yesterday