本文共 802 字,大约阅读时间需要 2 分钟。
《重构之美》之四
在开发框架时,若要支持扩展性,引入工厂方法或许会成为神来之笔。例如,在QueryWrapper类的addResource()方法中,需要创建一个IndexWriter对象。
public class QueryWrapper { public final void addResource(RequestContext context) { log(”Add new resource.”) IndexWriter writer = createIndexWriter(context); //… } protected IndexWriter createIndexWriter(RequestContext context){ return new IndexWriterImpl(context); } }根据新的需要,在使用QueryWrapper类时,需要对IndexWriter进行扩展。然而,因为某些原因,我们不能直接修改框架的源代码。此时,我们可以通过定义QueryWrapper以及IndexWriter类的子类,来达成这一目的:
public class QueryWrapperExtension extends QueryWrapper { @Override protected IndexWriter createIndexWriter(RequestContext context){ return new CustomedIndexWriterImpl(context); } }如果在addResource()方法中直接调用构造函数创建IndexWriter对象,则面对扩展的为难之处,可以想见。
本文转自wayfarer51CTO博客,原文链接:http://blog.51cto.com/wayfarer/458095,如需转载请自行联系原作者