상세 컨텐츠

본문 제목

Generic Singleton Factory Pattern

Java

by techbard 2016. 7. 25. 20:37

본문

반응형



# GenericSingletonFactory.java


public class GenericSingletonFactory {


    private static applySame<Object> IDENTITY = new applySame<Object>() {


@Override

public Object apply(Object arg) {

   return arg;

}

    };


    @SuppressWarnings("unchecked")

    public static <T> applySame<T> identityFunction() {

return (applySame<T>) IDENTITY;

    }


    public static void main(String[] args) {


String[] strings = { "x", "y", "z" };

applySame<String> sameString = identityFunction();


for (String s : strings) {

   System.out.println(sameString.apply(s));

}

Number[] numbers = {1, 2.0, 3L};

applySame<Number> sameNumber = identityFunction();

for (Number n : numbers) {

   System.out.println(sameNumber.apply(n));

}

    }

}


interface applySame<T> {

    T apply(T arg);

}



# 결과


x

y

z

1

2.0

3


반응형

관련글 더보기

댓글 영역