Sobes.tech
Junior — Middle

Can you name the main composition patterns in object-oriented design?

sobes.tech AI

Answer from AI

Main composition patterns in object-oriented design help create flexible and extensible systems by combining objects:

  • Composition — an object contains other objects and delegates part of its functionality to them. Unlike inheritance, composition allows changing behavior at runtime.

  • Delegation — an object passes the execution of a task to another object while maintaining control.

  • Decorator — dynamically adds new responsibilities to objects by wrapping them in other objects.

  • Strategy — allows selecting an algorithm for an object's behavior at runtime by using composition with strategy objects.

Example of composition in Java:

class Engine {
    void start() { System.out.println("Engine started"); }
}

class Car {
    private Engine engine = new Engine();
    void start() { engine.start(); }
}

Here, the Car class uses composition to include an engine and delegate its start method.

Can you name the main composition patterns in… - sobes.tech