티스토리 뷰

Java

Generic Singleton Factory Pattern

techbard 2016.07.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


댓글
댓글쓰기 폼
공지사항
Total
397,744
Today
8
Yesterday
27
«   2019/01   »
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
글 보관함