018-002-007

Delegation Pattern: Functionality Reuse

Hard

Problem Description

Delegation Pattern: Functionality Reuse

In this problem, you will create a program that holds a Printer instance as a field of ColorPrinter and reuses printing functionality by delegating processing to it, displaying the result to standard output.

Learning Objective: Understand delegation pattern and reuse functionality through delegation instead of inheritance

Overview

Delegation is a pattern where one object delegates processing to another object. It reuses functionality through "has-a" relationships instead of "is-a" inheritance relationships.

Specifications

Implement a printer system:

  1. Printer class:

    • void print(String text) - prints text (outputs "Printing: [text]")
  2. ColorPrinter class:

    • Holds Printer instance as private field (delegation)
    • Receives Printer instance in constructor
    • void printInColor(String text, String color) - adds color info and delegates
      • Output "Color: [color]"
      • Delegate actual printing to printer.print(text)
  3. Main class:

    • Create Printer instance
    • Create ColorPrinter instance using it
    • Print "Hello World" in "Red"

Output Format

Color: Red
Printing: Hello World

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up