011-003-013

Factory Method with Constructor Chain

Hard

Problem Description

Factory Method with Constructor Chain

In this problem: You will implement a design pattern combining private constructor chains and static factory methods in a Color class.

Learning Objective: Understand flexible object creation through combining factory method pattern with constructor chains

Overview

This pattern makes constructors private to prevent direct external creation, and provides static factory methods as the only way to create instances. Factory methods can have descriptive names, clearly expressing the creation intent.

Specifications

  • Color class: red (int), green (int), blue (int), name (String) fields
  • Private constructors (this() chain): Color(int r, int g, int b) and Color(int r, int g, int b, String name)
  • Static factory methods: of(int r, int g, int b), ofRed(), ofGreen(), ofBlue()
  • toString() returns color information

Output Format

Color[name=Custom, rgb=(128, 64, 255)]
Color[name=Red, rgb=(255, 0, 0)]
Color[name=Green, rgb=(0, 255, 0)]
Color[name=Blue, rgb=(0, 0, 255)]

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