同一个对象的重量级和轻量级版本

时间:2011-02-03 03:49:01

标签: java object

对于我们正在开发的项目,我们需要同一实体类的轻量级和重量级对象。我们有一个简单的解决方案,但需要从专家的角度知道是否有更好的解决方案。我们的解决方案如下:

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用于数据库处理部分。

3 个答案:

答案 0 :(得分:2)

这是一种可能的选择:

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

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

答案 1 :(得分:1)

另一个需要考虑的方法是使用委托的继承。

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. 您可以自由继承父类,因为您没有使用此选项jet
  2. 您只能展示出现的属性
  3. 您的对象与继承没有紧密耦合,这通常意味着您可以更轻松地更改您的实现。
  4. 缺点:

    1. 更多编码

答案 2 :(得分:1)

如果您有非功能性要求,您的代码应该可以轻松升级,我会使用装饰器模式。它看起来如下:

//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");
}

这是一个非常强大的模式,我希望我可以帮助你。

度过愉快的一天。