Prototype + Factory
Object Oriented Design Patterns Continuous Assessment 2
Summary of Problems and Solutions
Sno Problem Solution Pattern
1 Drink Store Item Quantity Display Synchronization
Observer
2 Initializing Stores and creation of StoreObjects Prototype + Factory
3 Vending Machine Control State State
4 Enter Coins Chain of Responsibility
PROTOTYPE
Detailed Presentation of most interesting problem
Problem
• Concrete StoreObject creation (DrinkBrand and Coin) logic are wrapped inside PropertyLoader.
– Inflexibility in creation logic.– Accommodating new kinds of StoreObjects is difficult.– If the current file based database is changed to other
persistent mechanisms, then the entire logic behind creation needs to be re-written.
Caveats
• While we are aware that problems exist among the following areas, those are not addressed in the current solution
– Two different property loaders still exist.– StoreItem objects are still constructed from
property loaders
Analysis of problem
• Creational and initialization logic for an object exists outside of the object.
• This is a CREATIONAL problem
Candidate Design Patterns
• Prototype– Specify the kinds of objects to create using a prototypical
instance and create new objects by copying this prototype.• Factory method– Define an interface for creating an object, but let
subclasses decide which class to instantiate.• Abstract Factory– Provide an interface for creating families of related or
dependent objects without specifying their concrete classes
Abstract Factory applicability
• The system should be independent of how its products are created, composed andrepresented
• The system should be configured with one of multiple families of products
• A family of related product objects is designed to be used together and you need to enforce this constraint
✗
✗
✔
Factory method applicability
• A class can’t anticipate the class of objects it must create
• A class wants its subclasses to specify the object it creates
• Classes delegate responsibility to one of several helper subclasses and you want to localize the knowledge of which helper class to delegate
✗
✗
✗
Prototype applicability
• The system should be independent of how its products are created, composed and represented
• The classes to instantiate are specified at runtime
• Avoid building a class hierarchy of factories that parallels the class hierarchy of products
✔
✔
✔
Initialize CashStore
Initialize DrinkStore
Static View – Status quo
• Concrete StoreObject creation (DrinkBrand and Coin) logic are wrapped inside PropertyLoader.
– Inflexibility in creation logic.– Accommodating new kinds of StoreObjects is difficult.
Problems come in bunches - revisit
Participant mapping
New static view
Modified Initialize Store - Cash
DEMO