当前位置: 代码迷 >> Java相关 >> 容易工程模式
  详细解决方案

容易工程模式

热度:27   发布时间:2016-04-22 19:13:47.0
简单工程模式

简单工厂模式

定义:专门定义一个类来负责创建其它类的实例,被创建的实例通常都具有共同的父类或接口;

意图:提供一个类,由它负责根据一定的条件创建某一具体类的实例;

 1 public class FactoryDemo{ 2     public static void main(String []args){ 3         IFruit fruit = Factory.getFruit("橘子"); 4         if(fruit!=null){ 5             System.out.println(fruit.get()); 6         } 7         else{ 8             System.out.println("你要的东西不存在"); 9         }10     }11 }12 13 interface IFruit{14     public String get();15 }16 17 class Factory{18     public static IFruit getFruit(String name){19         if(name.equals("苹果"))20         {21              return new Apple();22         }23         else if(name.equals("橘子"))24         {25              return new Orange();26         }27         else28         {29             return null;30         }31     }32 }33 34 class Apple implements IFruit{35     public String get(){36         return "采摘苹果";37     }38 }39 40 class Orange implements IFruit{41     public String get(){42         return "采摘橘子";43     }44 }

 

  相关解决方案