接口--工厂设计模式
interface Fruit{ //定义一个接口
public void eat();
}
class Apple implements Fruit{ //实现接口
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements Fruit{ //实现接口
public void eat() {
System.out.println("吃橘子");
}
}
class Factory{
public static Fruit getInstance(String className) {
if("apple".equals(className)) {
return new Apple();
}
if("orange".equals(className)) {
return new Orange();
}
return null;
}
}
public class Test {
public static void main(String[] args) {
Fruit f = Factory.getInstance("apple");
f.eat();
}
}
输出结果:
吃苹果
还没有评论,来说两句吧...