java学习之路-----设计模式---工厂模式

来源:互联网 发布:陌陌八格切图软件 编辑:程序博客网 时间:2024/06/05 06:17
 工厂模式:

看代码一切你就明白了


package test;


interface Fruit{
     public void eat();
     
}

class M implements Fruit{

     public void eat() {
          System. out.println("吃 MM" );
          
     }
     
}
class Gg implements Fruit{

     public void eat() {
          System. out.println("吃GG" );
          
     }
     
}    
     


class  Factory{
     
     public  static Fruit getInstance(String userName){
          Fruit fruit= null;
           if("mm" .equals(userName)){
              fruit= new M();
          }
          
           if("gg" .equals(userName)){
              fruit= new Gg();
          }
           return fruit;
     }
     
}

public class FactoryTest {
     
     public static void main(String[] args) {
          Fruit f= null;
          f=Factory. getInstance("mm");
          f.eat();
     }

}

结果:

吃 MM

工厂模式就是像工厂一样的生产东西(对象),你需要什么,就生产什么。

原创粉丝点击