How to reduce the usage of IF - ELSE by reflection

2019-08-29 10:18发布

I was trying to use reflection for the code of PizzaFactory Class so that I can remove the if else condition and make my code more dynamic. But I am not able to figure out how.

   Pizza.java
    package PizzaTrail;
   import java.util.List;

    //this is the main abstract factory which will be extended by the concrete factory 
    public abstract class Pizza {  public abstract List fetchIngredients(String Type); }


    PizzaFactory.java 
   package PizzaTrail;
   import java.util.List;

   //this is the concrete factory 
   public class PizzaFactory extends Pizza
   { 
        public static Pizza getConcretePizza(String PType)
        { 
          Pizza p=null;
          if (PType.equals("Cheese")) 
          {
                     p=new CheesePizza();
          } else if (PType.equals("Pepperoni")) 
          {
              p=new PepperoniPizza();
          }
           else if (PType.equals("Clam")) 
          {
               p = new CalmPizza();

           }
           else if (PType.equals("Veggie")) 
           {
               p= new VeggiePizza();

            }
            return(p); 
       }   
   }


     ChessePizza.java
     package PizzaTrail;

      import java.util.ArrayList;
      import java.util.List;

     public class CheesePizza extends Pizza {
      List ing = new ArrayList();
       @Override
       public List fetchIngredients(String Type)
       {
       ing.add("Ingredient : Shredded Mozzarella Cheese");
      ing.add("Ingredient : Peppers");
      ing.add("Ingredient : Feta cheese");
     ing.add("Ingredient : Pesto");
      return (ing);   
      }

    }

  }

Can anyone help me get the reflection used in the pizzaFactory class so that i can call the class CheesePizza, etc dynamically?

7条回答
男人必须洒脱
2楼-- · 2019-08-29 11:14
      //public static Pizza getConcretePizza(String PType){


      public static Pizza getConcretePizza(Class cType){


     /**
      *

      if (PType.equals("Cheese")) 
      {
                 p=new CheesePizza();
      }//..............  
       */


    Constructor  ctor = cType.getConstructor();
    Object object = ctor.newInstance();
    p = object; 


     //....
      }
查看更多
登录 后发表回答