Last active
July 23, 2020 14:30
-
-
Save bhawna94/fc1faab091372d81399f28de3b895dac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Step 1 : Create abstract and concrete classes | |
//abstract class Pizza | |
public abstract class Pizza { | |
public abstract void bakePizza(); | |
} | |
//CheesePizza subclass | |
public class CheesePizza extends Pizza { | |
@Override | |
public void bakePizza() { | |
//TODO | |
System.out.println("Bake Cheese Pizza"); | |
} | |
} | |
//VeggiePizza subclass | |
public class VeggiePizza extends Pizza { | |
@Override | |
public void bakePizza() { | |
//TODO | |
System.out.println("Bake Veggie Pizza"); | |
} | |
} | |
Step 2 : Create Pizza AbstractFactory interface or abstract class | |
public interface PizzaAbstractFactory { | |
public Pizza orderPizza(); | |
} | |
Step 3: Create Factory class for each subclass | |
public class CheesePizzaFactory implements PizzaAbstractFactory { | |
@Override | |
public Pizza orderPizza() { | |
return new CheesePizza(); | |
} | |
public class VeggiePizzaFactory implements PizzaAbstractFactory { | |
@Override | |
public Pizza orderPizza() { | |
return new VeggiePizza(); | |
} | |
Step 4: Create a consumer class that will provide the entry point for the client classes to create sub-classes. | |
public class PizzaFactory { | |
public static getPizza(PizzaAbstractFactory factory){ | |
return factory.orderPizza(); | |
} | |
} | |
Step 5: Write a simple test method and see how to use the abstract factory to get the instance of sub-classes. | |
public class DesignPatternExample { | |
public static void main(String[] args) { | |
Pizza cheesePizza = PizzaFactory.getPizza(new CheesePizzaFactory()); | |
Pizza veggiePizza = PizzaFactory.getPizza(new VeggiePizzaFactory()); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment