Last active
December 28, 2015 17:59
-
-
Save kamekoopa/7540361 to your computer and use it in GitHub Desktop.
型クラス?
This file contains 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
package acceptance; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Hoge { | |
static interface ToString<T> { | |
String str(T t); | |
} | |
static class IntToString implements ToString<Integer> { | |
@Override | |
public String str(Integer integer) { | |
return integer.toString(); | |
} | |
} | |
static class ListToStr<T> implements ToString<List<T>>{ | |
private final ToString<T> toStr; | |
ListToStr(ToString<T> toStr){ | |
this.toStr = toStr; | |
} | |
@Override | |
public String str(List<T> ts) { | |
StringBuilder sb = new StringBuilder(); | |
for(T t : ts) { | |
sb.append(toStr.str(t)).append(", "); | |
} | |
return sb.toString(); | |
} | |
} | |
static class UrlToString implements ToString<URL> { | |
@Override | |
public String str(URL url) { | |
return url.toString(); | |
} | |
} | |
public static <T> String toStr(T t, ToString<T> toStr) { | |
return toStr.str(t); | |
} | |
static interface Calc<T>{ | |
public T calc(T a, T b); | |
} | |
static class IntAdd implements Calc<Integer>{ | |
@Override | |
public Integer calc(Integer a, Integer b) { | |
return a + b; | |
} | |
} | |
static class IntMul implements Calc<Integer>{ | |
@Override | |
public Integer calc(Integer a, Integer b) { | |
return a * b; | |
} | |
} | |
static class StringAdd implements Calc<String>{ | |
@Override | |
public String calc(String a, String b) { | |
return a + b; | |
} | |
} | |
public static <T> T calc(T a, T b, Calc<T> calc){ | |
return calc.calc(a, b); | |
} | |
public static void main(String[] args) throws Exception { | |
toStr(10 , new IntToString()); | |
toStr(new URL(""), new UrlToString()); | |
toStr(new ArrayList<Integer>(), new ListToStr<>(new IntToString())); | |
calc(1, 2, new IntAdd()); | |
calc(1, 2, new IntMul()); | |
calc("a", "b", new StringAdd()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment