2012-04-23 53 views
0

这是场景。需要我的面向对象设计的帮助

public interface Processor{ 

    public void create(); 

    public void setDocuments(); 

    public abstract void prepareDocuments(); 

} 

public class ProcessorImpl implements Processor{ 

    public void create(){ 
     // Do something 
    } 

    public void setDocuments(){ 
     // Do something 
    } 

} 

public class ProcessorA implements ProcessorImpl{ 
    // this class will implement only once abstract 
    // method which is prepareDocuments() 

    public void prepareDocuments(){ 
     // prepare documents..and also 
     // set the Documents list which will be checked by create() 
     // method and then index will be created. 

    } 

} 


public class IndexGenerator{ 

    public static void main(String[] args){ 

     ProcessorA a = new ProcessorAImpl(); 
     a.create(); 
    } 
} 

简要背景....我正在开发一个通用的框架来处理所有Lucene索引相关的活动,其中包括创建索引,删除索引,更新doc和添加到索引中。除了创建文档之外,处理索引的所有逻辑都保持相同。每个索引都有不同类型的Document,因此我保留了prepareDocuments()方法抽象并为每个索引类型实施。

现在我想让所有的索引生成器类都简单地创建一个像ProcessorA一样的特定索引Processor的实例并调用create()方法。但问题是create()方法始终会查找文档列表empty/null,但prepareDocuments通过调用setDocuments()方法来设置文档。我知道有一些设计缺陷,我真的需要寻求OO大师的帮助。

感谢 李书福

回答

1

我不知道为什么你会得到空/空,因为没有足够的代码,从中我们可以推断出它。但是,对于你的问题我会模板方法设计模式去,decsribed例如这里:http://en.wikipedia.org/wiki/Template_method_pattern

我认为是即使你正在尝试做的。

Btw。 implements关键字仅用于接口。您在这里试着用它代替的extends

public class ProcessorA implements ProcessorImpl 
0

为了详细说明以前的答案(即我完全同意)关于模板,这听起来像你可能有顺序的问题,其中setDocuments()被被称为。模板方法模式的好处之一是强制调用不同方法(抽象或不抽象)的顺序。

您可以考虑重组的基础类是这样的:

public interface Processor { 
    ... 
    // This method orchestrates doc preparation by ensuring the correct 
    // ordering of method invocation, and calls the derived class impl 
    // method doPrepareDocuments() 
    public void prepareDocuments() { 
     // do document creation stuff here by calling 
     // appropriate methods (abstract or not) 

     setDocuments(); 

     // implemented in derived classes to do specific document preparations 
     doPrepareDocuments(); 
    } 

    public abstract void doPrepareDocuments(); 
    ... 
} 

这样每一个派生类中实现不必须记住所有的步骤要采取,以及以什么顺序,而是侧重于它知道什么。这种方法增加了凝聚力。