3

我这里有一个框架,它使用一个对象在其他对象与之交互时维护它们之间的状态。我希望与状态交互的对象(“动作”)通常可以接受一种接口类型,状态对象将实现该接口,但我无法完成这项工作。

我想根据特定的状态实现(或接口)来定义框架对象本身,并且能够向它添加操作,只要它们直接或通过状态实现的接口接受定义的状态。

据我了解,该<? super S>定义的意思是“某种类型是 S 的父类”,但我不确定由 S 实现的接口是否符合此描述,因为它不完全是父类。

这是一个示例(不完全编译代码):

Class Framework<State> {
    addAction(Action<? super State> a) {} // adds to a list of actions to be run

    run(State s) {
        for(Action<? super State> a : actions) {
            a.perform(s);
        }
    }
}

Interface IState1 {}

Interface IState2 {}

Interface Action<State> {
    public void perform(State s);
}

Class Action1 implements Action<IState1> {}

Class Action2 implements Action<IState2> {}

Class CombinedState implements IState1, IState2 {}

public static void run() {
    Framework<CombinedState> f = new Framework<CombinedState>();

    // add is expecting Action<? super CombinedState> but getting Action<IState1>
    f.add(new Action1()); // This doesn't seem to work
    f.add(new Action2());

    f.run(new CombinedState());
}

出于泛型的目的,接口是否算作父类?有什么方法可以实现不需要反射吗?

4

1 回答 1

0
import java.util.ArrayList;

class State{}

class Framework<State> 
{
    public ArrayList< Action< ? super State > >actions = new ArrayList< Action< ?super State > >();

    void add(Action<? super State> a) {

        actions.add(a);

    } 

    void doRun(State s) {
        for(Action<? super State> a : actions) {
            a.perform(s);
        }
    }
}

interface IState1 {}

interface IState2 {}

interface Action<State> {
    public void perform(State s);
}

class Action1 implements Action<IState1> {
    public void perform( IState1 s )
    {
        System.out.println("Do something 1");
    }
}

class Action2 implements Action<IState2> {

    public void perform( IState2 s )
    {
        System.out.println("Do something 2");
    }   
}

class CombinedState implements IState1, IState2 {}

class Untitled {
    public static void main(String[] args) 
    {
         Framework<CombinedState> f = new Framework<CombinedState>();

            // add is expecting Action<? super CombinedState> but getting Action<IState1>
            f.add(new Action1()); // This doesn't seem to work
            f.add(new Action2());

            f.doRun(new CombinedState());
    }
}

这在 OSX 上的 CodeRunner 中运行。

于 2012-08-27T21:39:35.100 回答