Factory Method
How It Is Applied
Users log three kinds of outdoor activity — running, hiking and cycling. Every log goes through the same steps: validate the data, calculate the calories burnt, and save it, but each activity validates and counts calories its own way. Instead of the main logging process deciding which object to build, each activity type has its own logger: when a user picks hiking, the HikingLogger creates a HikingActivity, and the logging process uses it without knowing its exact type.
Justification
A new activity, such as padel, only needs its own logger and activity class — the existing logging process does not change. Factory Method also makes the code easier to test and maintain, lets the same code work with existing and new activity classes, and lets several developers work on different activities at the same time.
Classes
ActivityLogger (abstract) defines logActivity(), createActivity() and saveActivity(). RunningLogger, HikingLogger and CyclingLogger override createActivity() to return a RunningActivity, HikingActivity or CyclingActivity, each implementing the Activity interface’s validate() and calculateCalories().
Expected Benefits
- ▹New activity types are added without editing the logging process.
- ▹Each activity keeps its own validation and calorie rules in one class.
- ▹Loggers and activities can be tested on their own.
Class Diagram