设计可复用的库和框架
library和framework被称为系统层面的复用,是因为它们不仅定义了可复用的接口/类,并且定义了这些类之间的交互关系、调用关系
术语
API:应用编程接口,库和框架的接口
client:使用api的code
plugin:定制框架的客户端代码
extension point:框架内预留的空白,开发者开发出符合接口要求的代码,框架可调用,从而相当于开发者扩展了框架的功能
protocol:客户和api之间预期的交互序列
callback:框架将调用一个插件方法来访问定制功能
lifecycle method:根据协议和插件状态按顺序调用的回调方法
API设计
一个好的api
api should do one thing and do it well
有一个好的名字
api should be as small as small
implementation should not impact api
documentation matters
consider performance consequence
api must coexist peacefully with platform
classes should be immutable unless there’s a good reason to do otherwise
subclass only where it makes sense
api should fail fast: report errors as soon as possible
framework设计
白盒框架
通过继承和overriding实现,使用的是模板模式
黑盒框架
通过implementing接口实现,使用的是策略模式和观察者模式
在代码内部,框架会使用delegation调用这个接口的实现类的实例的方法