工厂模式

interface FruitInterface {
   void eat();
}

class Apple implements FruitInterface{

  @Override
   public void eat() {
     // TODO Auto-generated method stub
    System.out.println( "吃苹果");
  }

}

public class Orange implements FruitInterface{

  @Override
   public void eat() {
     // TODO Auto-generated method stub
    System.out.println( "吃橘子");
  }

}

public class Factory {
   //定义工厂类
public static FruitInterface getInstance(String className){
  FruitInterface fruit = null;
    
   if ( "Apple".equals(className)) { //将字符串放在前面能够避免空值
    fruit = new Apple();
  } if ( "Orange".equals(className)) {
    fruit = new Orange();
  }    
    
   return fruit;
    
}
}
public class FirstDemo {

   /**
    * 工厂设计模式
    */

   public static void main(String[] args) {
    FruitInterface fruitInterface = Factory.getInstance( "Apple");
    fruitInterface.eat();
    FruitInterface fruitInterface2 = Factory.getInstance( "Orange");     fruitInterface2.eat();   } }
相关文章
相关标签/搜索