Kelly's journey to a coding master

Singleton patterns 본문

Design Patterns

Singleton patterns

개발하는 통계학도 켈리 2023. 5. 3. 13:36

Singleton(싱글톤) is on of the Creational patterns(생성 패턴).

 

Then, what is Creational Patterns(싱글톤)?

-  Abstract the instantiation process and hide the details of object interfaces

- Give flexibility in what gets created, who creates it, how it gets created and when.

- ex) Singleton, Factory Method, Abstract Factory, Builder, etc.

 

What is Singleton pattern(생성 패턴)?

Briefly, Singleton pattern can be described as "one and only one instance of a particular class".

 

Purpose

- Ensure a class has only one instance for the duration of the system. (메모리 낭비 방지)

- Provide a global point of reference to the singleton. (데이터 공유)

structure of singleton pattern

 

Implementation example

public class CarClass {
	
	private static CarClass car = new CarClass(); //creating car instance just once, also it's set as private
	
	private CarClass() {} //constructor is private
	
	public static CarClass getInstance() { //can access the car instance through getInstance() method
		return car;
	}
	
	private static boolean isUse = false;

	public static void drive() { //차 사용 시작
		isUse = true;
		System.out.println("start driving");
	}
	
	public static void parking() { //차 사용 종료
		isUse = false;
		System.out.println("parking");
	}
	
	public static boolean isEnableUseCar() { //차 사용 가능한지
		return !isUse;
	}
	
}

'Design Patterns' 카테고리의 다른 글

Factory Method & Abstract Factory  (0) 2023.05.03