I learned how to use the builder ,factory ,and abstract factory.
- Where would I prefer to use the builder instead of Factory? and the opposite?(Please use examples in answer ) -- 2)What are the differences between the 2 builder approaches that I wrote in Main?
The First lines of codes in Main, is the first approach. I wrote it with Interfaces,abstract classes for models, builder interface + concrete specific builders that implelment the builder interface, and a director that constructs everything together.
The Second approach is where it written Car car = new Car(); in Main. I just wrote a class for Car + CarBuilder class inside with method build();, and I can add any attribute that I want . The second approach is very fast to write, and feels very flexible to me, not like the first approach- which feels very complex.
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("***** // Builder Pattern Demo // ******");
Director director = new Director();
MealBuilder vegMealBuilder = new VegMealBuilder();
MealBuilder nonVegMealBuilder = new ChickenBurgerBuilder();
director.construct(vegMealBuilder);
Meal vegMeal = vegMealBuilder.getMeal();
//veg meal builder
System.out.println("\nVegetarian Meal\n");
vegMeal.showItems();
System.out.println("Total Cost: " + vegMeal.getCost());
director.construct(nonVegMealBuilder);
Meal nonVegMeal = nonVegMealBuilder.getMeal();
System.out.println("\nNon Vegetarian meal\n");
nonVegMeal.showItems();
System.out.println("Total Cost : " + nonVegMeal.getCost());
//Other Approach For Builder Pattern
System.out.println("\n-------Other Approach For Builder Pattern---------\n");
Car car = new Car.CarBuilder("Honda", "civic", 3000).isNew(false).wheelsNum(2).build();
System.out.println(car.toString());
Car car2 = new Car.CarBuilder("Mazda", "3", 5000).wheelsNum(4).build();
System.out.println(car2.toString());
}
}
Thank you .
Aucun commentaire:
Enregistrer un commentaire