代码:
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呀?
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呀?
}
你的接口里没定义apple中的age,和grape的hasGood呀,那怎么用.
只有这样:
public interface Fruit {
public void grow();
public void plant();
public void harvest();
public void age();
public void hasGood();
}