ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ์‹ฑ๊ธ€ํ†ค(Singleton)
    ๐Ÿ’ป IT Study/Knowledge 2020. 7. 23. 18:17

     

     

    P U R P O S E

    ์ „์ฒดํ”„๋กœ๊ทธ๋žจ์—์„œ ๋‹จ ํ•˜๋‚˜์˜ ๊ฐ์ฒด๋งŒ ๋งŒ๋“ค๋„๋ก ๋ณด์žฅ.

    ํด๋ž˜์Šค ์™ธ๋ถ€์—์„œ new ์—ฐ์‚ฐ์ž๋กœ ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์—†๋„๋ก ๋ง‰์•„์•ผ ํ•œ๋‹ค. 

    why? ์ƒ์„ฑ์ž๊ฐ€ ํ˜ธ์ถœํ•œ๋งŒํผ ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋˜๊ธฐ ๋•Œ๋ฌธ์— ํ•˜๋‚˜์˜ ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๋‹ค. 


    H O W ?

    1. ์ƒ์„ฑ์ž ์•ž์— private ์ ‘๊ทผ์ง€์ •์ž(Modifier)๋ฅผ ์ด์šฉํ•œ๋‹ค. 

    -> private์„ ํ†ตํ•ด ์™ธ๋ถ€์—์„œ ํ˜ธ์ถœ์„ ๋ง‰์„ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค. 

     

    2. ์ •์ ํ•„๋“œ(static)๋ฅผ ์„ ์–ธํ•˜๊ณ  ์ž์‹ ์˜ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

    ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ new ์—ฐ์‚ฐ์ž๋กœ ํ˜ธ์ถœ ๊ฐ€๋Šฅ

    ๋‹จ, ์ •์ ํ•„๋“œ์—์„œ ์ ‘๊ทผ์ œํ•œ์ž๋ฅผ private์œผ๋กœ ํ•  ๊ฒƒ.

     

    3. ์™ธ๋ถ€์—์„œ ํ˜ธ์ถœํ•  ๋•Œ๋Š” ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ๋‹ค. (์™ธ๋ถ€์—์„œ ๊ฐ์ฒด๋ฅผ ์–ป๋Š” ์œ ์ผํ•œ ๋ฐฉ๋ฒ•)

    getInstance๋ฅผ ์„ ์–ธํ•˜๊ณ  ์ •์  ํ•„๋“œ์—์„œ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” ์ž์‹ ์˜ ๊ฐ์ฒด๋ฅผ ๋ฆฌํ„ด. 


    ์™ธ๋ถ€์—์„œ ์—ฌ๋Ÿฌ๊ฐœ์˜ ํด๋ž˜์Šค ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋„ ์ฃผ์†Œ๊ฐ€ ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•˜๊ฒŒ ๋œ๋‹ค. 

    ์•„๋ž˜ ์ฝ”๋“œ์—์„œ ํ™•์ธํ•˜๊ธธ ๋ฐ”๋ž€๋‹ค. 

     

    * java

    class Example {
    
    	}
    
    class Singleton {
    	// new๋ฅผ ํ•œ๋ฒˆ๋งŒ ํ˜ธ์ถœํ•˜๊ณ  ์‹ถ๋‹ค. 
    	// private static Singleton single = new Singleton(); 
    	static Singleton single;
    	
    	private Singleton () {
    		System.out.println("== default constructor ==");
    	}
    	
    	public static Singleton getInstance() {
    		if(single == null) {
    			single = new Singleton();
    		}
    		return single;
    	}
    }
    
    public class SingletonTest {
    	public static void main(String[] args) {
    		// ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ๋•Œ๋งˆ๋‹ค ์ฃผ์†Œ๊ฐ€ ๋‹ค๋ฅด๋‹ค. 
    		Example ex1 = new Example(); 
    		Example ex2 = new Example(); 
    		
    		System.out.println(ex1==ex2); 		
    		System.out.println(System.identityHashCode(ex1)); 		
    		System.out.println(System.identityHashCode(ex2)); 		
    
    		
    		// ๊ฐ์ฒด์˜ ์ฃผ์†Œ๊ฐ€ ๊ฐ™์•„์ง„๋‹ค. 
    		Singleton single1 = Singleton.getInstance();  			
    		Singleton single2 = Singleton.getInstance();   			
    		
    		System.out.println(single1==single2); 	
    		System.out.println(System.identityHashCode(single1));
    		System.out.println(System.identityHashCode(single2));
    		
    	}
    }
    

    ** ๊ฐ„๋‹จ ์ •๋ฆฌ

    ์‹ฑํดํ†ค(singleton) : ํ•˜๋‚˜์˜ application ์•ˆ์—์„œ ๋”ฑ ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ. 

    > ์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ํ•จ์œผ๋กœ์จ, ๊ฐ์ฒด์— ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์„ ๋ง‰๊ณ  ์™ธ๋ถ€์—์„œ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•œ๋‹ค. 

     

     

    ์ถœ์ € : ์ด๊ฒƒ์ด์ž๋ฐ”๋‹ค. 243p, ์ •์ง„๊ฐ•์‚ฌ๋‹˜ ์ˆ˜์—… 

    ๋Œ“๊ธ€

Designed by Tistory.