《重构之美》之四 

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

相关文章:

  • 2022-12-23
  • 2021-06-12
  • 2022-01-01
  • 2021-05-17
  • 2022-01-28
  • 2021-06-04
  • 2022-02-20
猜你喜欢
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-06-11
  • 2022-01-01
  • 2022-12-23
相关资源
相似解决方案