728x90
Singleton Pattern은 다음과 같다.
class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
public String getDescription(){return "I'm a Singleton!";}
}
public class Main {
public static void main(String[] args){
Singleton singleton = Singleton.getInstance();
System.out.println(singleton.getDescription());
}
}
멀티스레드일 경우 다음과 같은 문제점이 발생한다.
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private static ChocolateBoiler OnlychocolateBoiler = null;
//객체의 생성을 막음
private ChocolateBoiler(){
empty = true;
boiled = false;
System.out.println(this);
}
public static ChocolateBoiler getInstance(){
if(OnlychocolateBoiler==null){
OnlychocolateBoiler=new ChocolateBoiler();
}
return OnlychocolateBoiler;
}
public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// fill the boiler with a milk/chocolate mixture
}
}
public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
}
public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
}
public boolean isEmpty() {
return empty;
}
public boolean isBoiled() {
return boiled;
}
}
//MultiThread.java
public class MultiThread extends Thread{
private String name;
public MultiThread(String name) {
this.name = name;
}
public void run() {
int count = 0;
for(int i=0; i<5; i++) {
count++;
ChocolateBoiler chocolateBoiler = ChocolateBoiler.getInstance();
System.out.println(name+ "의"+ count+"번째 쓰레드의 singleton 객체 : " + chocolateBoiler.toString());
try {
Thread.sleep(400);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MultiThread AAA = new MultiThread("A");
MultiThread BBB = new MultiThread("B");
AAA.start();
BBB.start();
}
}
<출력결과>
B의1번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
A의1번째 쓰레드의 singleton 객체 : ChocolateBoiler@1e73dd
B의2번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
A의2번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
B의3번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
A의3번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
B의4번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
A의4번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
B의5번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
A의5번째 쓰레드의 singleton 객체 : ChocolateBoiler@150a7ec8
728x90
'기타 > Java' 카테고리의 다른 글
[Design Pattern]Adapter Pattern (0) | 2021.11.16 |
---|---|
[Design Pattern]Command Pattern (0) | 2021.11.16 |
[Java]Design Pattern-Decorator Pattern (0) | 2021.10.28 |
[Java]Design Pattern-Simple Factory (0) | 2021.10.28 |
[Java]Design Pattern-Abstract Factory (0) | 2021.10.27 |