본문 바로가기

Programming

Java enum class 자바 이넘 클래스 (Singleton design pattern 처럼 사용방법)


 앞에서 자바 싱글턴 디자인패턴을 썼는데.. ( 여 기 )


이어서 자바 enum 자료형 클래스에 대한 내용을 쓴다..


enum 자료형을 잘 써서 이런저런 경우에 대입하는 경우가 많은데,


일단은 이펙티브 자바에서 나온 싱글턴을 대체하는 enum 클래스 예제만 보자?



 I posted Java singleton pattern ( here )


Continue to post this enum class in Java..


There are many usage to use enum datatype in Java, 


for the first, Imma write enum class for singleton in effective java book. Let's get started?




 특이사항으로는.. 클래스 입구에 TEST 가 대문자로 써있는데,


대문자로 쓰는 것은 관습적인 것 같고.. 하나하나의 객체? 를 의미하는 것 같다.


enum class 를 쓰고 해당 객체의 이름을 쓰면, 그 객체로 바로 연결이 되는 개념.


싱글턴은 단 1개의 객체를 유지했다면, enum 클래스는 각기 다른 이름(대문자)의 객체로


같은 클래스이지만 다른 내용을 가진 객체를 전역으로 관리할 수 있다. 


예제에서는 싱글턴처럼 사용할 내용이라서 1개만 써둠.



 Hm.. one of interesting thing is that Enum class has to have uppercase instance name in the entrance of class (You can see TEST word in example code).


It means just name of instance you'll have. If you write name of that enum class and use that instance name, then you can call and use this class as one instance (The instance you named, it could be one or more)


 Singleton has just one instance for a class, but enum class can have many instances if you named a lot. And it's static instance.


 Imma write just one instance (TEST) in example code.




아무튼 그래서, enum class 자체에서 public/protected 생성자를 막아뒀고,


private 생성자에서 속성을 초기화 하거나 할수 있다.


가져다 쓰는건 클래스이름.객체이름.(함수이름 또는 변수이름 등) 으로 접근이 가능하다.


예제 보면서 대충 따라하면 이해 잘 안돼도 쓸 수 있게 만들어놨슴~



 Anyway, enum class blocked public/protected constructor, we can initialize attribute or do something in private constructor.


 And.. we can use attribute or method we made calling class name and instance name.


Y'all can understand easily seeing this example code.



Code.. let me see code!!!!


코드.. 코드를 보자!!!!!




e.g. 


public enum TestEnumClass {

TEST;


private int testInteger;


private TestEnumClass {

this.testInteger = 100;

}


public void printText() {

System.out.println("Test Print");

}


public void printInteger() {

System.out.println(this.testInteger);

}


public int getTestInteger() {

return this.testInteger;

}

public void setTestInteger(int testInteger) {

this.testInteger = testInteger;

}




public static void main(String args[]) {


TestEnumClass.TEST.printText();


TestEnumClass.TEST.printInteger();


TestEnumClass.TEST.setTestInteger(10000);


TestEnumClass.TEST.printInteger();

}

}




그 외에..




2018/10/11 - [Programming/Design Pattern ] - Design pattern - Singleton (디자인패턴 - 싱글턴)



2018/10/11 - [Programming/Java] - Java parse double dataType after dot, 자바 소수점 이하 출력개수 조절



2018/10/08 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #12 SortByHeight

2018/10/06 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #11 IsLucky

2018/10/03 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #10 CommonCharacterCount



2018/09/27 - [Programming/C++] - C++ Math - floor/ceil/round (내림/올림/반올림)