最简单的Java工厂设计模式样例

//工厂方法demo
interface Fruit{
   void Eat();

}
class Apple implements Fruit{
  public void Eat(){
    System.out.println("我在吃苹果");
  }
}
class Banana implements Fruit{
  public void Eat(){
    System.out.println("我在吃香蕉");
  }
}
class Factory{


  public static Fruit getinstance(String data){

    if("banana".equals(data)){
      return new Banana();
    }else if("apple".equals(data)){
      return new Apple();
    }else{
      return null;
    }
  }

}
public class factorydemo{
  public static void main(String [] args){
    Fruit f=Factory.getinstance("banana");
    f.Eat();
  }
}

程序运行结果如下:

D:\code\java>javac factorydemo.java

D:\code\java>java factorydemo
我在吃香蕉


你可能感兴趣的:(java学习笔记,工厂设计模式)