간단한 접근 방법은 리소스 번들에서 크기 별칭을로드하는 것입니다. 일부 예제 코드 (같은 패키지에있는 모든 파일을 넣어) :
인터페이스는 크기 속성
public interface Sized {
public String getSize();
}
제품 클래스
public class Product implements Sized {
private final String size;
public Product(String size) {
this.size = size;
}
public String getSize() {
return size;
}
@Override
public String toString() {
return size;
}
}
마법을 수행하는 비교기를 캡슐화 :
를
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
public class SizedComparator implements Comparator<Sized> {
// maps size aliases to canonical sizes
private static final Map<String, String> sizes = new HashMap<String, String>();
static {
// create the lookup map from a resourcebundle
ResourceBundle sizesBundle = ResourceBundle
.getBundle(SizedComparator.class.getName());
for (String canonicalSize : sizesBundle.keySet()) {
String[] aliases = sizesBundle.getString(canonicalSize).split(",");
for (String alias : aliases) {
sizes.put(alias, canonicalSize);
}
}
}
@Override
public int compare(Sized s1, Sized s2) {
int result;
String c1 = getCanonicalSize(s1);
String c2 = getCanonicalSize(s2);
if (c1 == null && c2 == null) {
result = 0;
} else if (c1 == null) {
result = -1;
} else if (c2 == null) {
result = 1;
} else {
result = c1.compareTo(c2);
}
return result;
}
private String getCanonicalSize(Sized s1) {
String result = null;
if (s1 != null && s1.getSize() != null) {
result = sizes.get(s1.getSize());
}
return result;
}
}
SizedComparator.properties :
1 = Small,tiny
2 = medium,Average
3 = Large,big,HUGE
(단지 행복 흐름) 단위 테스트 : ResourceBundles을 자동으로 캐시됩니다
import org.junit.Before;
import org.junit.Test;
public class FieldSortTest {
private static final String SMALL = "tiny";
private static final String LARGE = "Large";
private static final String MEDIUM = "medium";
private Comparator<Sized> instance;
@Before
public void setup() {
instance = new SizedComparator();
}
@Test
public void testHappy() {
List<Product> products = new ArrayList<Product>();
products.add(new Product(MEDIUM));
products.add(new Product(LARGE));
products.add(new Product(SMALL));
Collections.sort(products, instance);
Assert.assertSame(SMALL, products.get(0).getSize());
Assert.assertSame(MEDIUM, products.get(1).getSize());
Assert.assertSame(LARGE, products.get(2).getSize());
}
}
참고. 당신과 프로그래밍의 ResourceBundle를 다시로드 할 수 있습니다 :
ResourceBundle.clearCache();
(자바 1.6부터). 또는 일부 Spring magic을 사용하여 자동 다시로드 메시지 리소스를 만들 수 있습니다.
까다로운 속성 파일에서 읽는 것이 충분하지 않은 경우 데이터베이스에서 크기 별칭도 쉽게 유지할 수 있습니다.
@downvote : 질문에 대한 문제점을 알고 싶습니다. 다시 생각해 보겠습니다. – thedan
데이터가 어떻게 생겼는지에 대한 구체적인 예를 제시하는 것이 도움이 될 것이라고 생각합니다. –