๐ŸŒป JAVA/๋””์ž์ธ ํŒจํ„ด

5. ์‹ฑ๊ธ€ํ„ด (Singleton) ํŒจํ„ด - Head First Design Patterns

iseunghan 2020. 4. 6. 21:29
๋ฐ˜์‘ํ˜•

์ธ์Šคํ„ด์Šค ์ƒ์„ฑํ• ๋•Œ ์–ด๋–ป๊ฒŒ ํ• ๊นŒ? --------> new MyClass();

๋งŒ์•ฝ ์ƒ์„ฑ์ž๊ฐ€ private์œผ๋กœ ์„ ์–ธ๋ผ์žˆ์œผ๋ฉด? --------> ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ถˆ๊ฐ€.

์ƒ์„ฑํ•˜๊ฒŒ ํ•˜๋ ค๋ฉด?? --> ์ธ์Šคํ„ด์Šค๋ณ€์ˆ˜๋ฅผ static๋ณ€์ˆ˜๋กœ ๋ฏธ๋ฆฌ ์„ ์–ธํ›„ --> ์š”์ฒญ์‹œ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ

๋„˜๊ฒจ์ฃผ๋Š” ์‹์œผ๋กœ ์ƒ์„ฑํ•ด์ค€๋‹ค.

 

public class Singleton{
	private static Singleton uniqueInstance;
    
    private Singleton() { } // private๋กœ ์„ ์–ธ๋œ ์ƒ์„ฑ์ž
    
    public static Singleton getInstance() { //์ธ์Šคํ„ด์Šค ์ƒ์„ฑํ•˜๋Š” ๋ฉ”์†Œ๋“œ
    	if (uniqueInstance == null) { //์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋œ ์ ์ด ์žˆ๋Š”์ง€ ํ™•์ธํ›„
        		uniqueInstance = new Singleton();  //์ƒ์„ฑ
        }
        return uniqueInstance; //return
    }
}

 

 

 

์‹ฑ๊ธ€ํ„ด ํŒจํ„ด ์ •์˜ ) ์‹ฑ๊ธ€ํ„ด ํŒจํ„ด์€ ํ•ด๋‹น ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ํ•˜๋‚˜๋งŒ ๋งŒ๋“ค์–ด์ง€๊ณ ,

์–ด๋””์„œ๋“ ์ง€ ๊ทธ ์ธ์Šคํ„ด์Šค์— ์ ‘๊ทผํ• ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ธฐ ์œ„ํ•œ ํŒจํ„ด์ž…๋‹ˆ๋‹ค.

 

 

 

์‹ฑ๊ธ€ํ„ด ํŒจํ„ด :  ํด๋ž˜์Šค ๋‹ค์ด์–ด๊ทธ๋žจ

์‹ฑ๊ธ€ํ„ด ํŒจํ„ด : ํด๋ž˜์Šค ๋‹ค์ด์–ด๊ทธ๋žจ

 

 

์‹ฑ๊ธ€ํ„ด ํŒจํ„ด์˜ ๋ฌธ์ œ์ 

 

ChocolateBoiler boiler = new ChocolateBoiler.getInstance();

fill();
boil();
drain();
Thread1 Thread2 uniqueInstance
public static Chocolate getInstance()   null
  public static Chocolate getInstance() null

if(uniqueInstance == null)

 

 

if(uniqueInstance == null) *์•ˆ์ข‹์€ ์ƒํ™ฉ

null

null

uniqueInstance = new ChocolateBoiler();

return uniqueInstance;

 

 

 

 

 

 

 

uniqueInstance = new ChocolateBoiler();

 

return uniqueInstance;

 

<object1>

<object1>

 

 

<object2> ** ๋ฌธ์ œ ๋ฐœ์ƒ!

<object2> ** ๋ฌธ์ œ ๋ฐœ์ƒ!

 

 

 

๋ฉ€ํ‹ฐ์Šค๋ ˆ๋”ฉ ๋ฌธ์ œ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

 

1. synchronized ๋™๊ธฐํ™” ์‹œํ‚ค๊ธฐ.

public class Singleton{
		private static Singleton uniqueInstance;
        //๊ธฐํƒ€ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜
        
        private Singleton() {}
        
        public static synchronized Singleton getInstance(){
        		if(uniqueInstance == null){
                	uniqueInstance = new Singleton();
                 }
                 return uniqueInstance;
       }
       ....
}

๋‹จ์ ) ์—„์ฒญ๋‚œ ์†๋„ ์ €ํ•˜ ( ๋™๊ธฐํ™” ์‹œํ‚ค๋ฉด ์„ฑ๋Šฅ์ด 100๋ฐฐ ์ •๋„ ์ €ํ•˜ )

 

 

2. ์ฒ˜์Œ๋ถ€ํ„ฐ ์ธ์Šคํ„ด์Šค๋ฅผ ๋งŒ๋“ค์–ด ๋ฒ„๋ฆฌ๊ธฐ.

public class Singleton{
	public static Singleton uniqueInstance = new Singleton(); //!!
    
    private Singleton(){ }
    
    public static Singleton getInstance(){
    		return uniqueInstance;
    }
}

 

๋ฐ˜์‘ํ˜•