2012-08-27 91 views
3

我有一个框架,它使用一个对象来保持其他对象之间的状态,因为它们与它进行交互。我希望与状态交互的对象(“Actions”)可以一般接受State对象实现的一种类型的接口,但是我很难做这个工作。接口是否被认为是实现它的类的父类?

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

据我所知,<? 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()); 
} 

对于仿制药的目的,我们的接口算作父类?有什么办法可以实现这个不需要反射?

+3

为什么不试试看? – Antimony

+0

是否要接受从State接口扩展的对象? – Sednus

+0

我想接受能够直接使用CombinedState的Actions,或者因为CombinedState实现了他们接受的接口。 – Bracket

回答

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上运行。

+0

您虽然将State定义为一个类。这是必要的吗? – Bracket

+0

@Bcket:我也认为这没有必要。在'Framework '中,'State'只是一个类型参数(与'T'相同)。 – Natix

+0

哦,我感到很蠢。我在代码中使用“add”而不是“addAction”,这是我实际定义的。我现在感到很尴尬,因为我把它当作一个简单的错字。但看到它对你有用,让我意识到我的错误! – Bracket

相关问题