Search⌘ K
AI Features

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.

Solution explanation

  • Lines 2–22: We define three interchangeable formatting strategy classes: CasualGreetingStrategyFormalGreetingStrategy, and JsonGreetingStrategy.

    • Each implements a .format() method with its own message style.

    • CasualGreetingStrategy uses an informal greeting.

    • FormalGreetingStrategy builds a professional message including the title.

    • JsonGreetingStrategy outputs a structured JSON string.

  • Lines 25–38: The GreetingService class ...