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:
Printerclass:void print(String text)- prints text (outputs "Printing: [text]")
ColorPrinterclass:- Holds
Printerinstance as private field (delegation) - Receives
Printerinstance in constructor void printInColor(String text, String color)- adds color info and delegates- Output "Color: [color]"
- Delegate actual printing to
printer.print(text)
- Holds
Mainclass:- Create
Printerinstance - Create
ColorPrinterinstance using it - Print "Hello World" in "Red"
- Create
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