本文共 839 字,大约阅读时间需要 2 分钟。
interface Number {}class One implements Number {}class Two implements Number {}class Three implements Number {}class NumberFactory { final static Map> map = new HashMap<>(); static { map.put("one", One::new); map.put("two", Two::new); map.put("three", Three::new); } public static Number createNumber(String number) { Supplier numberSupplier = map.get(number); if (numberSupplier != null) return numberSupplier.get(); throw new IllegalArgumentException("No such product " + number); }}public class Main { public static void main(String[] args) { Number number = NumberFactory.createNumber("one"); Number number1 = NumberFactory.createNumber("two"); System.out.println(number.getClass()); System.out.println(number1.getClass()); }}
转载地址:http://vmjqi.baihongyu.com/