2012-04-23 33 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(); 
    ... 
} 

這樣每一個派生類中實現不必須記住所有的步驟要採取,以及以什麼順序,而是側重於它知道什麼。這種方法增加了凝聚力。