Author:
Composition⚓︎
Combine simple objects or functions to build more complex ones.
Composition - Black Box Reuse⚓︎
Object composition requires objects being composed have well-defined interfaces. Each object is treated as a "black box" that exposes certain methods or properties, while hiding its internal implementation details. This style of reuse is called "Black Box Reuse".
Advantages of Composition⚓︎
- Flexibility: Objects can be composed at runtime, allowing for dynamic behavior changes.
- Reusability: Able to get more complex functionality by combining simpler components.
- Maintainability: Changes to one component do not affect others.
- Avoids Inheritance Issues: Reduces problems associated with deep inheritance hierarchies. (Composition over Inheritance)
Example⚓︎
Let's use the above picture as an example. We have three simple objects:
Human,Head, andBody.
public class Head
{
public void Speak() => Console.WriteLine("Hello!");
}
public class Body
{
public void Walk() => Console.WriteLine("Walking...");
}
public class Human
{
private Head head = new Head();
private Body body = new Body();
public void Speak() => head.Speak();
public void Walk() => body.Walk();
}
var person = new Human();
person.Speak();
person.Walk();
#include <iostream>
class Head {
public:
void speak() { std::cout << "Hello!" << std::endl; }
};
class Body {
public:
void walk() { std::cout << "Walking..." << std::endl; }
};
class Human {
private:
Head head;
Body body;
public:
void speak() { head.speak(); }
void walk() { body.walk(); }
};
int main() {
Human person;
person.speak();
person.walk();
return 0;
}
