直接看代码了:

interface Fruit{    
public void grow();
public void eat();
}
class Apple implements Fruit{
public void grow(){
System.out.println("苹果在生长...");
}
public void eat(){
System.out.println("吃苹果...");
}
}
class Orange implements Fruit{
public void grow(){
System.out.println("橘子在生长...");
}
public void eat(){
System.out.println("吃橘子...");
}
}
class Banana implements Fruit{
public void grow(){
System.out.println("香蕉在生长...");
}
public void eat(){
System.out.println("吃香蕉...");
}
}
class Factory{
public static Fruit getFruit(String className){
Fruit f = null;
try{
f = (Fruit)Class.forName(className).newInstance();
}catch (Exception e){}
return f;
}
}
public class Demo07{
public static void main(String args[]){
Fruit f = Factory.getFruit("Banana");
f.grow();
}
}

  实际中是通过配置fruit.xml文件来保持包.类名称的此种代码是典型的配置与程序相分离,程序直接有配置文件有关。某一个部分的修改不影响其他程序。

--------------------------------------------------------------------

PS: 欢迎关注公众号"Devin说",会不定期更新Java相关技术知识。

--------------------------------------------------------------------

相关文章:

  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-24
  • 2022-12-23
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
  • 2021-05-27
  • 2021-06-18
相关资源
相似解决方案