๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš€ Backend

[Spring Basic] ์Šคํ”„๋ง ์‹ฑ๊ธ€ํ†ค

by dev.py 2024. 1. 18.

https://www.inflearn.com/course/์Šคํ”„๋ง-ํ•ต์‹ฌ-์›๋ฆฌ-๊ธฐ๋ณธํŽธ

์‹ฑ๊ธ€ํ†ค ํŒจํ„ด

  • ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ 1๊ฐœ๋งŒ ์žˆ๋Š” ๊ฒƒ์„ ๋ณด์žฅํ•˜๋Š” ๋””์ž์ธ ํŒจํ„ด
package hello.core.singleton;
public class SingletonService {

	//1. static ์˜์—ญ์— ๊ฐ์ฒด๋ฅผ ๋”ฑ 1๊ฐœ๋งŒ ์ƒ์„ฑํ•ด๋‘”๋‹ค.
	private static final SingletonService instance = new SingletonService();

	//2. public์œผ๋กœ ์—ด์–ด์„œ ๊ฐ์ฒด ์ธ์Šคํ„ด์Šค๊ฐ€ ํ•„์š”ํ•˜๋ฉด ์ด static ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์กฐํšŒํ•˜๋„๋ก ํ—ˆ์šฉํ•œ๋‹ค.
	public static SingletonService getInstance() {
         return instance;
	}
    
	//3. ์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ์„ ์–ธํ•ด์„œ ์™ธ๋ถ€์—์„œ new ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ ๊ฐ์ฒด ์ƒ์„ฑ์„ ๋ชปํ•˜๊ฒŒ ๋ง‰๋Š”๋‹ค. 
	private SingletonService() {
	}
    
	public void logic() { 
    	System.out.println("์‹ฑ๊ธ€ํ†ค ๊ฐ์ฒด ๋กœ์ง ํ˜ธ์ถœ");
	} 
}

๊ตฌํ˜„ ๋ฐฉ๋ฒ•

  1. static final ์ธ์ž๋กœ ๋ถˆ๋ณ€์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑ
  2. ์ƒ์„ฑ์ž๋ฅผ private ๋กœ ์„ ์–ธํ•˜์—ฌ ์™ธ๋ถ€์—์„œ์˜ ๊ฐ์ฒด ์ƒ์„ฑ์„ ๋ง‰๋Š”๋‹ค
  3. ํ•˜๋‚˜๋งŒ ์กด์žฌํ•˜๋Š” instance ๋ฅผ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•ด getInsatance ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

 

์žฅ์ 

  • ์„œ๋ฒ„ ์ƒ์„ฑ์‹œ์— ๋งŒ๋“ค์–ด์ง€๊ธฐ์— ์š”์ฒญ ์ฒ˜๋ฆฌ๊ฐ€ 
  • ๊ฐ์ฒด ํ•˜๋‚˜๋งŒ์„ ์ƒ์„ฑํ•˜๊ธฐ์— ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์•„๋‚„ ์ˆ˜ ์žˆ๋‹ค.
  • ๋‹ค๋ฅธ ์ธ์Šคํ„ด์Šค์™€ ๋ฐ์ดํ„ฐ ๊ณต์œ ๊ฐ€ ํŽธํ•˜๋‹ค (๋‹ค ์‹ฑ๊ธ€ํ†ค์ด๋ฉด ๋‹ค ์ „์—ญ)

 

ํ•˜์ง€๋งŒ ๋‹จ์  ๋งŽ๋‹ค

  • ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด ๊ตฌํ˜„ ์ฝ”๋“œ๊ฐ€ ์†์ด ๋งŽ์ด๊ฐ
  • ์˜์กด ๊ด€๊ณ„์ƒ, ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๊ตฌ์ฒด์— ์˜์กดํ•œ๋‹ค
  • ํ…Œ์ŠคํŠธ ํ•˜๊ธฐ ์–ด๋ ต๋‹ค
  • ๋‚ด๋ถ€ ์†์„ฑ ๋ณ€๊ฒฝ๊ณผ ์ดˆ๊ธฐํ™”๊ฐ€ ์–ด๋ ต๋‹ค.
  • private ์ƒ์„ฑ์ž ๋•Œ๋ฌธ์— ์ž์‹ ํด๋ž˜์Šค ๋งŒ๋“ค๊ธฐ๊ฐ€ ์–ด๋ ต๋‹ค
  • ์œ ์—ฐ์„ฑ์ด ๋–จ์–ด์ง„๋‹ค.

์ด๋Ÿฐ ๋งŽ์€ ๋‹จ์  ์žˆ์ง€๋งŒ

 

์Šคํ”„๋ง์ด ๋‹ค ํ•ด๊ฒฐํ•ด์ค€๋‹ค.

์Šคํ”„๋ง์—์„œ๋Š” ๊ธฐ๋ณธ์ด ์‹ฑ๊ธ€ํ†ค ์ปจํ…Œ์ด๋„ˆ์ด๋‹ค.

๋‹ค์Œ ๊ฐ•์˜ ๋‚ด์šฉ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์ •๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค.
https://www.inflearn.com/course/์Šคํ”„๋ง-ํ•ต์‹ฌ-์›๋ฆฌ-๊ธฐ๋ณธํŽธ