๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ—‚.๋Œ€์™ธํ™œ๋™/๐Ÿ“.์นด์นด์˜คํด๋ผ์šฐ๋“œ์Šค์ฟจ

[JAVA] Singleton Pattern

by ๐Ÿ’พ๊ณ ๊ตฌ๋งˆ๋ง›ํƒ•๋จน๊ณ ์‹ถ๋‹ค 2023. 12. 18.
728x90

๐Ÿ“ข Singleton Pattern

์‹ฑ๊ธ€ํ„ด ํŒจํ„ด: ๊ฐ์ฒด๋ฅผ ํ•˜๋‚˜๋งŒ ์ƒ์„ฑ ํ•˜๋„๋ก ํ•˜๋ฉฐ, ์ƒ์„ฑ๋œ ํ•œ ๊ฐœ์˜ ๊ฐ์ฒด๋ฅผ ๊ฐ€์ง€๊ณ  ์–ด๋””์—์„œ๋“ ์ง€ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ํŒจํ„ด์ด๋‹ค.
๊ฐ์ฒด ์ƒ์„ฑ์„ ํด๋ž˜์Šค์•ˆ์—์„œ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ์™ธ๋ถ€์—๋Š” ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค. 

๋”ฐ๋ผ์„œ ์ƒ์„ฑ์ž๋Š” private๋กœ ์„ ์–ธํ•ด์•ผํ•œ๋‹ค.

public class DuckManager {
	private static DuckManager manager = new DuckManager();
	private Duck[] ducks = new Duck[20];
	
	private DuckManager() {
		makeDucks();
	}
	
	public static DuckManager getDuckManager() {
		return manager;
	}
}

 

๐ŸŽจ ์‚ฌ์šฉ๋ฒ•

package mycom.duck.frame;

public class MyFrame extends Frame{
    public static int FRAME_WIDTH=800;
    public static int FRAME_HEIGHT=600;
    DuckManager duckManager;
    
    public MyFrame(){
    	duckManager = DuckManager.getDuckManager();
    	this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    	this.setVisible(true);
    }

    public void paint(Graphics g){
    	duckManager.displayAllDucks(g);
    	duckManager.flyAllDucks(g);
    	duckManager.swimAllDucks(g);
    	duckManager.quackAllDucks(g);
    }

}
728x90