引入工厂方法支持扩展

《重构之美》之四 

在开发框架时,若要支持扩展性,引入工厂方法或许会成为神来之笔。例如,在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对象,则面对扩展的为难之处,可以想见。

posted @ 2010-12-17 11:42  张逸  阅读(2449)  评论(2编辑  收藏  举报