2016-07-04 26 views
0

你好Stackoverflowers訪問方法,OOP非關聯類

我有5個班,富,酒吧,轟的一聲,咕嚕,ZOT。 Thud和Grunt實例是Bar的字段。 Foo實例是Thud的一個領域。

Foo,Thud和Grunt爲View準備數據(MVVM模式,它們是視圖模型)。 Foo和Zot是數據庫或創建它們(模型)

其中,Foo產生了一些在Grunt中列出的Zot(從Bar添加,從Thud訪問Foo)。我需要Foo在Grunt中獲得Zot的名單。如果可能,我想避免在Grunt或Bar類中完成所有工作(將序列化列表),因爲它們不是模型。這一過程將始終從美孚(添加新的類或東西當然是可能的)

public class Bar 
{ 
    Thud thud; 
    Grunt grunt; 

    Bar(Zot zotInstance) 
    { 
    new thud(); 
    new grunt(); 
    grunt.zotlist.add(zotInstance); 
    } 
} 

public class Thud 
{ 
    Foo foo; 
} 

public class Grunt 
{ 
    list<Zot> zotList; 
    public list<Zot> getList(); 
} 
public class Foo 
{ 
    public Zot makeZots() {}; 
    public void BringMeZots() // I would like a way to get the zotList when this method is called. 
} 

我不知道要解釋它的最簡單的方法。告訴我是否需要解釋我的問題。

回答

0

因此,您需要一種方法來共享您創建的Grunt對象。

首先,你需要一種方式來注入你的Foo類這樣的:

public class Foo 
{ 
    Grunt grunt; 

    public Foo(Grunt g) 
    { 
    grunt = g; 
    } 

    public Zot makeZots() 
    { 
    } 

    public void BringMeZots() 
    { 
    List<Zot> hereAreSomeZots = grunt.getList(); 
    } 
} 

這意味着你需要把它注入到你的Thud類也:

public class Thud 
{ 
    Foo foo; 

    public Thud(Grunt g) 
    { 
    foo = new Foo(g); 
    } 
} 

然後最後,你可以通過將此Grunt實例納入您的Thud實例中:

public class Bar 
{ 
    Thud thud; 
    Grunt grunt; 

    Bar(Zot zotInstance) 
    { 
    grunt = new Grunt(); 
    grunt.zotlist.add(zotInstance); 
    thud = new Thud(grunt); 
    } 
} 

你有非常抽象的類名,所以我很難分辨這些實際上正在做什麼,但通常當我看到需要傳遞的依賴關係時,它會告訴整體設計的問題。

你應該看看依賴注入,因爲這也會簡化你的設計。