2009-12-07 47 views
2

我想做一個視圖類,提供一個水平或垂直佈局取決於它是如何創建的。我正在使用委託來實現此目的。黑莓 - 樂趣與FieldManagers

class View extends Manager { 
    private Manager mDelegate; 

    public View(Manager inDelegate) { 
     mDelegate = inDelegate; 
     // the delegate is the only child of "this" manager. 
     super.add(mDelegate); 
    } 

    public void add(Field f) { 
     // all other children go into the delegate.  
     mDelegate.add(f); 
    } 

    // other methods that also delegate 

} 

當我實例化一個View對象時,我傳入一個水平或垂直字段管理器,然後委託調用。這是Screen類在黑莓中所做的。

其實我在看黑莓文檔的屏幕上看到什麼叫它代表(所以我可以模仿)和我注意到像這樣在視屏通話...

保護布爾keyChar(焦ç ,int狀態,int time)

將密鑰生成事件委派給焦點受控字段。 此方法在此屏幕的代理管理器上調用Manager.keyChar(char,int,int)。

那麼它馬上就會對我產生影響,他們如何在屏幕的代表上調用受保護的方法?或者是文檔錯誤,這種方法沒有被委託?

任何人都知道他們是如何完成的?

回答

0

我在其他一些SO問題的幫助下設法解決了這個問題。

我的解決方案是創建一個接口,爲受保護的方法提供公共接入點,然後對Manager類進行子類化並在該接口中進行混合。然後公共方法將調用其超級受保護的方法。

然後,View類將被傳遞給其中一個Manager子類。

public interface ManagerDelegate { 
    Manager asManager(); 
    // Provide public access points to any protected methods needed. 
    void doProtectedMethod(); 
} 

public HorizontalDelegate extends HorizontalFieldManager implements ManagerDelegate { 
    public Manager asManager() { 
     return this; 
    } 
    public void doProtectedMethod() { 
     // call the Manager's protected method. 
     protectedMethod(); 
    } 
} 

public VerticalDelegate extends VerticalFieldManager implements ManagerDelegate { 
    public Manager asManager() { 
     return this; 
    } 
    public void doProtectedMethod() { 
     // call the Manager's protected method. 
     protectedMethod(); 
    } 
} 

public class View extends Manager { 
    private final ManagerDelegate mDelegate; 

    public View(ManagerDelegate inDelegate) { 
     mDelegate = inDelegate; 
    } 

    protected void protectedMethod() { 
     // Call into our delegate's public method to access its protected method. 
     mDelegate.doProtectedMethod(); 
    } 

    public void publicMethod() { 
     // For public delegated methods I can just get the Manager instance from 
     // the delegate and call directly. 
     mDelegate.asManager().publicMethod(); 
    } 
} 
0

提醒自己what protected means

受保護的方法可以通過 同級車中的任意子類調用,但不是不相關的類 。

這並不直接回答你的問題,但你能延長ScreenAPI here),而不是Manager,然後調用構造函數super(mDelegate)?那麼大概什麼樣的魔法纔有用?

除此之外,我只是建議你嘗試一下,看看你是否可以重寫所謂的受保護的方法!