Solution: Format Greetings in Multiple Styles
Explore how to implement and switch between multiple greeting formats dynamically using the Strategy Pattern. Learn to create separate formatting strategies and delegate message creation through a flexible context class. By the end, you will understand how to build a greeting service that easily adapts to changing formatting needs without modifying existing code.
We'll cover the following...
Solution explanation
Lines 2–22: We define three interchangeable formatting strategy classes:
CasualGreetingStrategy,FormalGreetingStrategy, andJsonGreetingStrategy.Each implements a
.format()method with its own message style.CasualGreetingStrategyuses an informal greeting.FormalGreetingStrategybuilds a professional message including the title.JsonGreetingStrategyoutputs a structured JSON string.
Lines 25–38: The
GreetingServiceclass ...