Created
May 3, 2012 01:00
-
-
Save fumokmm/2582301 to your computer and use it in GitHub Desktop.
enumでインタフェースを実装するテスト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import static org.junit.Assert.*; | |
| import static org.hamcrest.CoreMatchers.*; | |
| import java.util.List; | |
| import java.util.ArrayList; | |
| import org.junit.Test; | |
| public class EnumTest { | |
| @Test | |
| public void enumでインタフェースの実装テスト() { | |
| // 用意したenumは 動物 と 食べ物 | |
| assertThat(Animal.class.getSimpleName(), is("Animal")); | |
| assertThat(Food.class.getSimpleName(), is("Food")); | |
| // #values() で全要素が取得可能 | |
| assertArrayEquals(new Animal[]{ | |
| Animal.cat, Animal.tiger, Animal.lion, | |
| Animal.goat, Animal.sheep | |
| }, Animal.values()); | |
| assertArrayEquals(new Food[]{ | |
| Food.rice, Food.bread, Food.noodle | |
| }, Food.values()); | |
| // さていよいよインタフェースを利用する。 | |
| // 動物も食べ物も色がついているものを実装しているので、色がついているものとして扱える | |
| for (Colored whiteThing : new Colored[]{ | |
| Animal.goat, Animal.sheep, Food.rice | |
| }) { | |
| assertThat(whiteThing.getColor(), is("白")); | |
| } | |
| // 茶色いものリストを用意して | |
| List<Colored> brownThings = new ArrayList<Colored>(); | |
| brownThings.addAll(collectBrown(Animal.values())); | |
| brownThings.addAll(collectBrown(Food.values())); | |
| // 茶色いものを確認 | |
| assertArrayEquals(new Colored[]{ | |
| Animal.cat, Animal.lion, Food.bread | |
| }, brownThings.toArray(new Colored[brownThings.size()])); | |
| } | |
| /** | |
| * 茶色だけに絞って返却 | |
| * @param Coloredな配列 | |
| * @return 茶色なColoredのリスト | |
| */ | |
| private List<Colored> collectBrown(Colored[] coloredList) { | |
| List<Colored> result = new ArrayList<Colored>(); | |
| for (Colored colored : coloredList) | |
| if (colored.getColor().contains("茶")) | |
| result.add(colored); | |
| return result; | |
| } | |
| } | |
| // ↓ 色付けされたものを表現するインタフェース | |
| interface Colored { | |
| String getColor(); | |
| } | |
| // ↓ プライベートコンストラクタでごにょごにょする実装 | |
| enum Animal implements Colored { | |
| cat("白と黒と茶"), // ねこ | |
| tiger("黄と黒"), // とら | |
| lion("茶"), // らいおん | |
| goat("白"), // やぎ | |
| sheep("白"), // ひつじ | |
| ; | |
| private String color; | |
| private Animal(String color) { this.color = color; } | |
| @Override public String getColor() { return this.color; } | |
| } | |
| // ↓ 直接インタフェースを実装してしまってもいい | |
| enum Food implements Colored { | |
| rice { @Override public String getColor() { return "白"; } }, // こめ | |
| bread { @Override public String getColor() { return "白と茶"; } }, // ぱん | |
| noodle { @Override public String getColor() { return "白"; } }, // めん | |
| ; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment