美文网首页Java学习笔记系列
Effective Java Item1 - 静态工厂方法

Effective Java Item1 - 静态工厂方法

作者: SonyaBaby | 来源:发表于2018-01-28 23:34 被阅读0次

手持一本英文版的技术书,感觉还是有点不一样的。整理出每篇的要点以便于回顾。

Consider static factory methods instead of  constructors 

考虑用静态工厂方法去替代构造器

核心当你想要使用public构造器时,请先考虑一下我们好用的静态工厂方法

优点:

1.和构造器比起来,静态工厂方法它们是有名字的。

栗子1:

public static Boolean valueOf(boolean b) {

    return b ? Boolean.TRUE : Boolean.FALSE;

}

2.和构造器比起来,静态工厂每次在被调用的时候不需要创建新的对象。

3.和构造器比起来,静态工厂方法可以返回任意一个返回类型的子类型。

4.静态工厂方法可以在实例化参数时减少冗余。

Map<String, List<String>> map = new HashMap<String, List<String>>

public static <K, V> HashMap<K, V> newInstance(){

       return new HashMap<K, V>;

}

Map< String, List< String>> map = HashMap.newInstance();

当然到1.8都还没有这个静态方法,但我们可以加入到自己的utils类中呢,还可以自定义一些参数balabala

缺点:

1.仅提供静态工厂而没有public或protected域构造器的类是不能够被子类化的。

Tip:

什么是子类化

2.静态工厂方法并没有和其他静态方法区别开。

不过我们在自己写静态方法的时候可以按照如下通用名字,来命名自己想要使用的静态工厂方法,比如valueOf,of,getInstance,newInstance,getType

A service provider framework:

a service interface  

a provider registration API 

a service access API

a service provider interface

类比于JDBC

Connection  is the service interface 

DriverManager.registerDriver is the provider registration API 

DriverManager.getConnection is the service access API

Driver is the service provider interface

Ending:

今日运动打卡:

WTF?  Such 逼格(BIG)?

相关文章

网友评论

    本文标题:Effective Java Item1 - 静态工厂方法

    本文链接:https://www.haomeiwen.com/subject/apzzaxtx.html