1. Static Variable
변수에 static 키워드를 붙이면 메모리 할당을 딱 한번만 하게되어 메모리 사용에 이점을 준다.
스태틱 변수는 같은 곳의 메모리 주소만을 바라보기 때문에 값을 공유하게 된다.
None Static Variable
class Test{
static int count = 0;
int test(){
return count++;
}
}
------------------------------------------------
class Test2{
Test test = new Test();
Test test2 = new Test();
int result1 = simms.test(); //result1 = 0
int result2 = simms2.test(); //result2 = 1
}
Static Variable
class Test{
int count = 0;
int test(){
return count++;
}
}
------------------------------------------------
class Test2{
Test test = new Test();
Test test2 = new Test();
int result1 = simms.test(); //result1 = 0
int result2 = simms2.test(); //result2 = 0
}
2. Static Method
메소드 앞에 static 키워드를 붙이면 [Class].[Method]와 같이 객체 생성없이 클래스를 통해 메서드를 직접 호출할 수 있다.
None Static Method
Class Test{
String testMethod(){
return "Test";
}
}
----------------------------------------------------------------
Class Test2{
Test test = new Test();
String result = test.testMethod();
}
Static Method
Class Test{
static String testMethod(){
return "Test";
}
}
----------------------------------------------------------------
Class Test2{
String result = Test.testMethod();
}
3. Singleton Pattern
디자인 패턴중 하나로써, 단 하나의 객체만을 생성하게 강제하는 패턴
1. private 생성자 생성
private 키워드를 사용했기 때문에 다른 클래스에서 Singletone 클래스에 접근할 수 없다.
어디서도 사용할 수 가 없다.
class Singleton{
private Singleton(){
}
}
----------------------------------------------------------------
public class Test{
public static void main(String[] args){
Singleton singletone = new Singletone(); // Compile Error
}
}
2. Singletone 클래스 반환
이제 다른 클래스에서 getInstance 메소드로 접근이 가능하다.
하지만 이또한 getInstance 메소드를 호출할 때마다 새로운 객체가 생성되기 때문에 싱글톤이 아니다.
class Singleton{
private Singleton(){
}
public static Singleton getInstance(){
return new Singletone();
}
}
----------------------------------------------------------------
public class Test{
public static void main(String[] args){
Singleton singletone1 = Singletone.getInstance();
Singleton singletone2 = Singletone.getInstance();
// singletone1 == singletone2 는 False
}
}
3. Singletone
이제 다른 클래스에서 호출을 하여도 onlyOnde이라는 객체에 들어있는 Singletone이 반환된다.
이로써 단 하나의 객체만을 가지는 Singletone이 되었다.
class Singleton{
private static Singletone onlyOne;
private Singleton(){
}
public static Singleton getInstance(){
if(onlyOne == null) onlyOne = new Singletone();
return onlyOne;
}
}
----------------------------------------------------------------
public class Test{
public static void main(String[] args){
Singleton singletone1 = Singletone.getInstance();
Singleton singletone2 = Singletone.getInstance();
// singletone1 == singletone2 는 True
}
}
반응형
'Java' 카테고리의 다른 글
Consumer (0) | 2023.02.09 |
---|---|
Try-With-Resources (0) | 2023.02.09 |
Access Modifier ( 접근 지정자 ) (0) | 2023.02.08 |
ThreadLocal (0) | 2023.02.07 |
Stream (0) | 2023.01.31 |