The Factory Design Pattern - Defines and interface for creating an object, but lets subclasses decide which class to instantiate. Factory pattern lets a class defer instantiation to subclasses.
This pattern gives a way to encapsulate the instantiations of concret types.
Example: Consider a product Pizza. There are different types of pizza.CheesePizza, VegPizza, ChickenPizza. These are subtypes of the product Pizza. Taking Pizza as a class, CheesePizza, VegPizza and ChickenPizza are the sub classes of Pizza.
Now, let's take the case of a PizzaStore where people order pizza. The main objective of a PizzaStore is to cater to customers who order pizzas. People place order and PizzaStore irrespective of whatever pizza was ordered by the customer, need to cater to the customer.
Thus, PizzaStore uses the product Pizza. PizzaStore has operations such as orderPizza. The process of instantiating which type of pizza can be isolated from the PizzaStore.
class VegPizza extends Pizza{
}
abstract class PizzaStore {
factoryMethod();
orderPizza(){ }
}
The factory method can be implemented by classes inherting PizzaStore, such as NewYorkStylePizzaStore or CaliforniaStylePizzaStore, thereby creating NewYorkStyleCheesePizza ot CaliforniaStyleCheesePizza.
Design Principle: Depend upon abstractions. Do not depend upon concrete classes.
Abstract Factory Pattern: Provides an interface for creating families of related or dependant objects without specifying their concrete classes.
Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.
6) Depend on abstractions. Do not depend on concrete classes.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment