java--面向对象--设计模式--工厂模式

今天第一次接触Java的工厂设计模式,我可是闻名已久啊。 

看下面: 

Java代码  收藏代码
  1. interface Fruit  
  2. {  
  3.     public void eat();  
  4. }  
  5. class Apple implements Fruit  
  6. {  
  7.     public void eat()  
  8.     {  
  9.         System.out.println("吃苹果");  
  10.     }  
  11. }  
  12. class Orange implements Fruit  
  13. {  
  14.     public void eat()  
  15.     {  
  16.         System.out.println("吃桔子");  
  17.     }  
  18. }  
  19. class Factory  
  20. {  
  21.     public static Fruit getIns(String classname){  
  22.         Fruit f;  
  23.         f = null;  
  24.         if ("apple".equals(classname))  
  25.         {  
  26.             f = new Apple();  
  27.         }  
  28.         if ("orange".equals(classname))  
  29.         {  
  30.             f = new Orange();  
  31.         }  
  32.         return f;  
  33.     }  
  34. }  
  35.   
  36. public class  Demo6  
  37. {  
  38.     public static void main(String[] args)   
  39.     {  
  40.         Fruit f;   
  41.         if (args[0]!=null){  
  42.         f=Factory.getIns(args[0]);  
  43.             f.eat();  
  44.         }  
  45.         else {  
  46.             System.out.println("请输入参数");  
  47.         }  
  48.     }  
  49. }  



程序在子类与接口之间加入了一个过渡段,通过过渡段来取得接口的实例,这个过渡段就叫做工厂。 

那么是不是可以这样理解,工厂就是把主方法提供的东西加工成符合标准的产品(实例化对象)以供后面的程序处理呢?

原文地址:https://www.cnblogs.com/huyayuan1/p/4715525.html