📌 싱글톤 패턴이란?
- 프로그램에서 인스턴스가 단 한 개만 생성되어야 하는 경우 사용하는 디자인 패턴
- static 변수, 메서드를 활용하여 구현 할 수 있음
📌 싱글톤 패턴으로 회사 객체 구현하기
- 생성자는 private 으로 선언
private Company() {}
- 클래스 내부에 유일한 private 인스턴스 생성
private static Company instance = new Company();
- 외부에서 유일한 인스턴스를 참조할 수 있는 public 메서드 제공
public static Company getInstance() {
if(instance == null) {
instance = new Company();
}
return instance;
}
🍀 CompanyTest.java
public class CompanyTest {
public static void main(String[] agrs) {
Company company1 = Company.getInstance();
Company company2 = Company.getInstance();
System.out.println(company1);
System.out.println(company2);
//Calendar calendar = Calendar.getInstance();
}
}
Singleton |
- instance |
- Singleton + getInstance |
싱글톤이라는 클래스이름에 프라이빗 인스턴스 멤버 변수 ,
싱글톤이라는 프라이빗 생성자 , 퍼블릿 겟인스턴스 생성자
예제 < 설명에 따른 객체를 구현하여 테스트 코드가 실행되도록 구현하기>
- 자동차 공장이 있다. 자동차 공장은 유일한 객체이고, 이 공장에서 생산되는 자동차는 제작될 때마다 고유한 번호가 부여된다.
자동자 번호가 10001부터 시작되어 자동차가 생산될 때마다 10002, 10003 이렇게 번호가 붙도록 자동차 공장 클래스 , 자동차 클래스를 구현해라.
다음 CarFactoryTest.java 테스트 코드가 수행되도록 한다.
CarFactoryTest.java
public class CarFactoryTest {
public static void main(String[] args) {
CarFactory factory = CarFactory.getInstance();
Car mycar = factory.createCar();
Car yourcar = factory.createCar();
System.out.println(mycar.getCarNum()); // 10001 출력
System.out.println(yourcar.getCarNum()); // 10002 출력
}
}
여기서 factory 를 보면 new 를 하지 않고 getInstance()로 가져왔다. 그러므로 싱글폰 패턴으로 작성해보면 된다.
createCar() 메스드가 있다 이 createCar()에서 Car 를 new해서 반환해주면 된다. 여기서 객체가 생성된다. (즉 객체를 생성해주는 메서드를 따로 만들어주면 된다)
이를 생성할 때 시리얼넘버를 붙여주면 된다
=> 셋다 같은 package 안에서 작성한다.
CarFactory.java
public class CarFactory {
private static CarFactory instance = new CarFactory();
private CarFactory() {}
public static CarFactory getInstance() {
if(instance == null){
instance = new CarFactory();
}
return instance();
}
public Car createCar() {
Car car = new Car();
return car;
}
}
Car.java
public class Car {
private static int serialNum = 10000;
private int carNum;
public Car() {
serialNum++;
carNum = serialNum;
}
public int getCarNum() {
return carNum;
}
public void setCarNum(int carNum){
this.carNum = carNum;
}
}
728x90
반응형
'java공부' 카테고리의 다른 글
[객체지향프로그래밍] static 응용 - 싱글톤 패턴(singleton pattern) (0) | 2022.04.12 |
---|---|
[객체지향프로그래밍]11_static 변수 (0) | 2022.02.19 |
[객체지향프로그래밍]10_객체 간의 협력 (collaboration) (0) | 2022.02.19 |
[객체지향프로그래밍]09_객체 자신을 가리키는 this (0) | 2022.02.19 |
[객체지향프로그래밍]08_캡슐화(encapsulation) (0) | 2022.02.19 |