Factory Pattern in Apex
Factory Pattern is one of the most commonly used design pattern. Think of a scenario where you have a factory which generates both mobile phones and laptops. For a user visiting your factory all they have decide if they want to buy either Mobile or Laptop . If for instance they like to buy mobile phone you will sell them mobile phones. Similarly, if they would like to buy a laptop your factory will sell them a laptop.





We will use the similar concept in the code. Let say you have a method which return URL.
www.google.com or www.facebook.com. So Calling method do not have to care about the underlying interface of URL all they care is they want respective URL.
Lets implement this
First we will need an interface
Lets create facebook and google class
Lets create a factory class
You can use enum as well instead of boolean as getfactory param. If you have more than 2 classes to instantiate then you need to use enum.
The way you call your code is
This will return google.com
if you change the param of getfactory to false you will get facebook.com
Comments
Post a Comment