2011-02-03 57 views
1

對於我們正在開發的項目,我們需要同一個實體類的輕量級和重量級對象。我們有一個簡單的解決方案,但需要從專家的角度來了解是否有更好的解決方案。我們的解決方案如下:同一個對象的重量級和輕量級版本

public interface User{ 

//Some variables and methods 

} 

public class LightWeightUser implements User{ 

//Lightweight code goes here 

} 

public class HeavyWeightUser implements User{ 

//HeavyWeight code goes here 

} 

我們計劃使用hibernate進行數據庫處理部分。

+0

正在執行延遲加載不夠好的解決方案嗎?雖然它的一個建議,延遲加載大多數時間起作用。只需將可選參數標記爲延遲加載即可。 – 2011-02-03 03:54:12

回答

2

這裏是一個可能的選擇:

public class User { 
    //Light-weight code goes here. 
} 

public class HeavyWeightUser extends User { 
    // Heavy-weight code goes here. 
} 
1

另一種形式給出考慮是使用代表團insted的繼承。

public class HeavyWeightUser { 
//HeavyWeightUser properties here 
//.... 
private User user; 
//exposing user properties here 
public Something getUserProperty(){return something;} 
public void serUserProperty(Something something){this.user.setSomething(something);} 
} 

這有喜歡的優點:

  1. 你可以自由地繼承形式的父類,因爲你沒有使用此選項的噴氣
  2. 你可以只露出特性使得SENCE
  3. 你的對象並不像繼承那麼緊密,通常意味着你可以更輕鬆地改變你的實現。

缺點:

  1. 更多編碼
1

我會使用Decorator模式這一點,如果你有你的代碼應該是很容易升級的非功能性需求。它看起來如下所示:

//first define a basic layout for your class 
public abstract class User{ 
     public abstract String foo(String bar); 
} 

//then extend it and implement real behavior 
public class concreteUser extends User { 
    public String foo(String bar) { 
     ... 
    } 
} 

//now comes the interesting part... the decorator. At first we need to define a layout for our decorators, that extends your implementation 
public abstract class UserDecorator extends User { 
    @Override 
    public abstract String foo(String bar); 
} 

//now you are ready to do everything you want 

有了這個3類你現在可以開始「裝飾」在你的類中的每個可能的方式重量級和輕量級行爲。讓我們有一個例子,並創建一個裝飾:

public class AsdfUserDecorator extends UserDecorator { 
    private final User user; 

    public AsdfUserDecorator(User user) { 
     this.user = user; 
    } 

    @Override 
    public String foo(String bar) { 
     //do stuff 
     ... 
     //propagate everything to other decorators (this is the magic) 
     return foo(user.foo(bar)); 
    } 

    private String additionalHeavyweightStuff(String asdasd) { 
     return blubb; 
    } 
} 

//and another one 
public class QwerUserDecorator extends UserDecorator { 
    //no changes in the class in this example... its the same as AsdfUserDecorator.... 
    private final User user; 

    public AsdfUserDecorator(User user) { 
     this.user = user; 
    } 

    @Override 
    public String foo(String bar) { 
     //do stuff 
     ... 
     //propagate everything to other decorators (this is the magic) 
     return foo(user.foo(bar)); 
    } 

    private String additionalHeavyweightStuff(String asdasd) { 
     return blubb; 
    } 
} 

現在,你可以裝飾一個用戶用下面的代碼:

public static void main(String args[]) { 
    User user = new concreteUser(); 
    user = new AsdfUserDecorator(user); 
    user = new QwerUserDecorator(user); 
    user.foo("sadf"); 
} 

這是一個非常強大的模式,我希望我可以幫助你。

祝您有愉快的一天。