《重构之美》之四 

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

作者: 张逸 发表于 2010-12-17 11:42 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"