Java 8下的工厂模式

来源:互联网 发布:win7网络小图标不见了 编辑:程序博客网 时间:2024/06/16 13:25

Java 8下的工厂模式

你肯定厌倦了传统工厂模式的switch或者if else 模式, 如下

public static Factory{  public Sample creator(String string){    switch(string){      "apple": return new Apple();      "car": return new Car();      "plane": return new Plane();    }  }}其中 Apple, Car, Plane 均继承 Sample

但是,你有不能使用Map,这样会造成,不必要的内存开销。

不过Java8的到来,函数成为了一等功能,那就不一样了。

我们来改写上面的列子

public static Factory{  final static Map<String, Supplier<Sample>> map = new HashMap<>();  static {    map.put("apple", Apple::new);    map.put("car", Car::new);    map.put("plane", Plane:: new);  }  public static Sample creator(String string){    Supplier<Sample> supplier = map.get(string);    if(supplier != null) return supplier.get();    throw new IllegalArgumentException("无效参数");  }}

这儿我们利用了函数的懒加载特性。只用当supplier.get()调用时,Sample的子类才初始化,这样就不会多占用内存。当然这也精简了你的代码。

0 0
原创粉丝点击