代码:
Fruit.java
public interface Fruit {  public void grow();  public void plant();  public void harvest();
}Apple.java
public class Apple implements Fruit {  public void grow() {
    log("Apple grow");
  }  public void plant() {
    log("Apple plant");
  }  public void harvest() {
    log("Apple harvest");
  }  public void age() {
    log("Apple age");
  }  private void log(String message) {
    System.out.println(message);
  }
}Grape.java
public class Grape implements Fruit {  public void grow() {
    log("Grape grow");
  }  public void plant() {
    log("Grape plant");
  }  public void harvest() {
    log("Grape hatvest");
  }  public void hasGood() {
    log("Grape Good");
  }  private void log(String message) {
    System.out.println(message);
  }
}FactoryFruit.java
public class FactoryFruit {  public static Fruit factory(String type) {
    if(type.equalsIgnoreCase("Apple")) {
      return new Apple();
    }
    else if(type.equalsIgnoreCase("Grape")) {
      return new Grape();
    }
    return null;
  }
}StaticFactoryTeste.java
public class StaticFactoryTester {
  public static void main(String[] args) {
    Fruit fruit;    fruit = FactoryFruit.factory("Apple");
    fruit = new Apple();
    fruit.grow();
    fruit.plant();
    fruit.harvest();
    fruit.age();  //这里有问题
    fruit = FactoryFruit.factory("grape");
    fruit.grow();
    fruit.plant();
    fruit.harvest();   
  }
}我用简单工厂生成了fruit(听说声明成接口好扩展)
我如果访问apple中的age,和grape的hasGood呀?

解决方案 »

  1.   

    instanceof and down casting
      

  2.   

    public interface Fruit {public void grow();public void plant();public void harvest();
    }
    你的接口里没定义apple中的age,和grape的hasGood呀,那怎么用.
    只有这样:
    public interface Fruit {
    public void grow();
    public void plant();
    public void harvest();
    public void age();
    public void hasGood();
    }
      

  3.   

    cenlmmx(学海无涯苦作舟) 但是age()只能有apple才有亚,怎么办呢?
      

  4.   

    好的设计是说你的子类不应该提供比接口或者父类更多的public函数,如果一定需要调用子类的某个函数,那只能照二楼所说,强制转换了.
      

  5.   

    那就是你的设计太差,不可能用了接口又来downcast
      

  6.   

    (apple)fruit = FactoryFruit.factory("Apple");向下转换有一定的风险