In this article, I will express the code that behaves the same as the Enum (enumeration) type without using the Enum type. Java's Enum (enumeration) type is a type that keeps multiple constants together. A set of fixed constants such as blood type, gender, moon name, constellation, and various codes can be coded based on object-oriented thinking. In addition, you can use useful functions by default. This time, I will explain using the Trump mark (spades, hearts, diamonds, clubs) as an example.
Suit.java
public enum Suit {
SPADE("♠"), HEART("♡"), DIAMOND("♢"), CLUB("♣");
private String symbol;
private Suit(String symbol){
this.symbol = symbol;
}
public String getSymbol(){
return symbol;
}
}
Suit.java
public class Suit implements Comparable<Suit>{
public static final Suit SPADE = new Suit("SPADE", "♠");
public static final Suit HEART = new Suit("HEART", "♡");
public static final Suit DIAMOND = new Suit("DIAMOND", "♢");
public static final Suit CLUB = new Suit("CLUB", "♣");
private static final List<Suit> VALUES =
Collections.unmodifiableList(
Arrays.asList(SPADE, HEART, DIAMOND, CLUB)
);
private final String name;
private final String symbol;
private Suit(String name, String symbol){
this.name = name;
this.symbol = symbol;
}
public String getSymbol(){
return symbol;
}
@Override
public int compareTo(Suit t){
return Integer.valueOf(this.ordinal()).compareTo(t.ordinal());
}
public Class<? extends Suit> getDeclaringClass(){
return this.getClass();
}
public String name(){
return name;
}
public int ordinal(){
return VALUES.indexOf(this);
}
@Override
public String toString(){
return name();
}
public static Suit valueOf(String name){
for(Suit value : VALUES){
if(value.name.equals(name)) return value;
}
throw new IllegalArgumentException();
}
public static List<Suit> values() {
return VALUES;
}
}
The List part is written like this.
private static final List<Suit> VALUES =
Collections.unmodifiableList(
Arrays.asList(SPADE, HEART, DIAMOND, CLUB)
);
In this part, the member variable VALUES is assigned an invariant list with four marks (Suit) as elements. I will explain each function.
When using Enum type and
private Suit(String symbol)
When not in use
private Suit(String name, String symbol)
The arguments of the constructor are different. The reason is that there is no way to get the variable names of the member variables used in the toString function and the valueOf function (values are SPADE, HEART, DIAMOND, CLUB of each character string) using the function. Therefore, it is necessary to keep it in the class via an argument.
[New Refactoring-Safely Improve Existing Code- (OBJECT TECHNOLOGY SERIES)](Fixed link: http://amzn.asia/c5WxOUh)
Recommended Posts