2

如果我有这样的课程:

class Foo implements HasBarMethod {
  public double bar(double x) {
    return x*x;
  }
}

我现在有

Foo foo = new Foo();
someObjectOutputStreamToSomeFile.writeObject(foo);

执行。后来我决定更改 Foo 的定义,如下所示:

class Foo implements HasBarMethod {
  public double bar(double x) {
    return x+x;
  }
}

是否可以这样做:

HasBarMethod foo = (HasBarMethod)someObjectInputStreamFromSameFile.readObject();

HasBarMethod 没有改变。现在我想从 foo.bar(x) 中得到 x 的平方,而不是总和。这可能吗?

当然,我应该使用不同的名称创建不同的类 Foo1、Foo2、...,作为一种好习惯。如果我正在制作一个包含不同类型博客的网站,我会这样做。但是考虑到我正在做实验性的东西(很多数字和很多解释它们的方法),如果不同的 Foo 类只会有小的适应

4

2 回答 2

1

Java 序列化保存字段。方法的说明保存在类文件中。

也许考虑保存不同的类文件和不同的类加载器,或者使用字节码库根据输入文件进行小的更改,尽管这两者可能比仅仅为不同的行为使用不同命名的类要复杂得多。

于 2012-12-18T14:48:30.647 回答
1

If I got the question right, you want to implement a class whose behavior changes dynamically, depending on the situation. You can implement one of the common patterns (sorry, don't remember its name):

//create function objects
class Sum implements HasBarMethod{
    public double bar(double x) {
        return x+x;
    }
}

class Multiply implements HasBarMethod{
    public double bar(double x) {
        return x*x;
    }
}

//create the base class
class DynamicBehavior{
    private HasBarMethod strategy;
    //other class fields

    public DynamicBehavior(HasBarMethod strategy){
        this.strategy = strategy;
        // ...
    }

    public double bar(double x) {
        return strategy.bar(x);
    }

    //you may want to handle strategy change in a different way.
    //this here is just a simple example.
    public setStrategy(HasBarMethod strategy){
        this.strategy = strategy;
    }

    //any code implementing strategy changes or whatever
}

This will allow you to change the strategies your class uses depending on its state or any other conditions you may wish to take into consideration.

An example of its usage:

public static void main(String args[]){
    HasBarMethod defaultStrategy = new Sum();
    DynamicBehavior dyn = new DynamicBehavior(defaultStrategy);


    if( /*condition*/ ){
        dyn.setStrategy(new Multiply());
    }

    double result = dyn.bar(5);
}

You might as well want to turn your strategy function objects into static fields of the base class as this will save you some memory and time by avoiding creation of their new instances each time you decide to switch strategies.

于 2012-12-18T14:56:03.960 回答