不同接口的设计模式

时间:2014-09-08 12:26:06

标签: java design-patterns

我对设计模式有疑问。我感谢任何帮助。

我实现了以下接口和类:

IType :没有方法,因为实现的类具有不同的数据类型和不同的参数。

public interface IType extends IType_1, IType_2 {}

IType_1

public interface IType_1 {
      public List<Object1> getDataType_1(List<String> list1, List<String> list2);   }

Strategy_1

public class Strategy_1 implements IType_1(List<String> list1, List<String> list2) {

@Override
public List<Object1> getDataType_1() {
    return object1;
}   }

IType_2

public interface IType_2 {
      public List<Object2> getDataType_2(List<Object2> obj);   }

Strategy_2

public class Strategy_2 implements IType_2(List<Object2> obj) {

@Override
public List<Object2> getDataType_2() {
    return object2;
}   }

我试图通过

创建策略

策略

public class Strategy {

public Strategy() {}

public IType createStrategy(int strategyNo) {
    IType strategy = null;
    switch(strategyNo) {
    case 1: 
        strategy = (IType) new Strateg_1();
    case 2: 
        strategy = (IType) new Strateg_2();
    }
    return strategy;
}    }

......但它没有用。

当我运行Strategy()类时,不会创建策略。

我得到一个例外,我运行该程序。

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
The method getDataType_1(List<String>, List<String>) is undefined for the type IType

问题是IType扩展了IType_1和IType_2。所以对象策略并不真正了解IType。而且我不知道如何解决它以使策略知道IType。

我想要实现的是在需要时创建Strategy_1或策略_2。在创建Stategy之后,我想使用它的方法。

非常感谢。

2 个答案:

答案 0 :(得分:0)

您的问题是,Strateg_1不是IType

IType是IType_1,但IType_1不是IType

IType是IType_2,但IType_2不是IType

你可以改为:

public interface IType_1 extends IType {....}


public interface IType_2 extends IType {....}

答案 1 :(得分:0)

  1. 这不起作用,你有什么错误?
  2. 看看这里:

    public class Strategy_1 implements IType_1(List<String> list1, List<String> list2)

    此行无效,因为此(List<String> list1, List<String> list2)不应该在那里

  3. 您无法将Strateg_1投放到IType,因为Strateg_1没有实现它

  4. 我建议你尽可能摆脱IType_1IType_2,并设置界面

    public interface IType<OBJECT> { 
        public List<OBJECT> getDataType(List<String> list1, List<String> list2); 
     }
    

    和实施

    public class Strategy_1 implements IType<Object1>{
    ...
    }
    
    public class Strategy_2 implements IType<Object2>{
    ...
    }
    
相关问题