package com.company.design.singleton;
public class SocketClient {
// static으로 하여 생성자 없이 객체를 생성할 준비를 함
private static SocketClient socketClient = null;
// default 생성자를 막아서 외부에서 SocketClient 객체 생성을 막음
private SocketClient() {
}
// getInstance를 static으로 생성하여 생성자 없이 객체에 접근하도록 만듬
public static SocketClient getInstance() {
if (socketClient == null) {
socketClient = new SocketClient();
}
return socketClient;
}
public void connect() {
System.out.println("connect");
}
}
AClazz, BClazz 생성(Class는 예약어이기에 ss대신 zz를 사용)
package com.company.design.singleton;
public class AClazz {
private SocketClient socketClient;
public AClazz() {
this.socketClient = SocketClient.getInstance();
}
public SocketClient getSocketClient() {
return this.socketClient;
}
}
package com.company.design.singleton;
public class BClazz {
private SocketClient socketClient;
public BClazz() {
this.socketClient = SocketClient.getInstance();
}
public SocketClient getSocketClient() {
return this.socketClient;
}
}
Main에서 Test
package com.company.design;
import com.company.design.singleton.AClazz;
import com.company.design.singleton.BClazz;
import com.company.design.singleton.SocketClient;
public class Main {
public static void main(String[] args) {
AClazz aClazz = new AClazz();
BClazz bClazz = new BClazz();
SocketClient aClient = aClazz.getSocketClient();
SocketClient bClient = bClazz.getSocketClient();
System.out.println("두개의 객체가 동일한가?");
System.out.println(aClient.equals(bClient));
}
}
package com.company.design.singleton;
public class SocketClient {
// static으로 하여 생성자 없이 객체를 생성할 준비를 함
private static SocketClient socketClient = null;
// default 생성자를 막아서 외부에서 SocketClient 객체 생성을 막음
public SocketClient() {
}
// getInstance를 static으로 생성하여 생성자 없이 객체에 접근하도록 만듬
public static SocketClient getInstance() {
if (socketClient == null) {
socketClient = new SocketClient();
}
return socketClient;
}
public void connect() {
System.out.println("connect");
}
}
package com.company.design.singleton;
public class AClazz {
private SocketClient socketClient;
public AClazz() {
//this.socketClient = SocketClient.getInstance();
this.socketClient = new SocketClient();
}
public SocketClient getSocketClient() {
return this.socketClient;
}
}
package com.company.design.singleton;
public class BClazz {
private SocketClient socketClient;
public BClazz() {
//this.socketClient = SocketClient.getInstance();
this.socketClient = new SocketClient();
}
public SocketClient getSocketClient() {
return this.socketClient;
}
}