Miguel Domingos
Miguel Domingos

Reputation: 353

Factory Pattern can't understand why the factory

Looking at this example: http://www.codeproject.com/Articles/68670/The-Factory-Pattern

Why can't I instantiate the concrete objects using Reflection like I show bellow, instead of having the extra work of creating a factory?

private Bat OrderBat(string choice)
{
   Bat myBat = Reflection.NewObject(choice);


   myBat.clean();
   myBat.applyGrip();
   myBat.applyLogo();
   myBat.applyCover();
   myBat.pack();

   return myBat;
}

Upvotes: 0

Views: 95

Answers (1)

mantrid
mantrid

Reputation: 2840

that only works when

1) choice string directly maps to a Bat class names

2) all Bat classes have default no-argument constructor

imagine that one day some new Bat classes have extra arguments like e.g. color:

switch (choice) {  
   case "hardball-yellow": 
      myBat = new HardBallColoredBat(Color.YELLOW); 
      break; 

   case "hardball-white": 
      myBat = new HardBallColoredBat(Color.WHITE); 
      break; 

   case "softball": 
      myBat = new SoftBallBat(); 
      break; 
}

by having all this extra code in a factory you can easily modify code for creation of new bats without going throught all the code that uses it.

Upvotes: 2

Related Questions