...

/

Solution: Format Greetings in Multiple Styles

Solution: Format Greetings in Multiple Styles

Implement interchangeable formatting strategies and delegate message creation through a configurable GreetingService context.

We'll cover the following...

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 ...