Junior
What is composition in the context of programming?
sobes.tech AI
Answer from AI
Composition is a structural design pattern that allows objects to be combined into tree structures to represent part-whole hierarchies. Composition enables clients to work with individual objects and their groups uniformly.
Key elements:
- Component: Interface or abstract class for all objects in the structure (both primitive and composite).
- Leaf: Primitive objects that have no children.
- Composite: Objects that contain child components (both Leaf and Composite).
Example: file system.
Component: common interface for "file element".Leaf: class "File".Composite: class "Folder". A folder can contain both Files and other Folders.
Client code can work with any "file element" (either a file or a folder) through the common interface Component, without knowing its specific type.
Advantages:
- Simplifies client code through a unified interface.
- Easy to add new component types.
- Represents hierarchical structures.
Disadvantages:
- It may be difficult to restrict the types of components that can be part of composite objects.
// Common interface for components
interface Component {
void operation();
}
// Leaf - primitive component
class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void operation() {
System.out.println("Leaf " + name + " operation.");
}
}
// Composite - can contain other components
import java.util.ArrayList;
import java.util.List;
class Composite implements Component {
private String name;
private List<Component> children = new ArrayList<>();
public Composite(String name) {
this.name = name;
}
public void add(Component component) {
children.add(component);
}
public void remove(Component component) {
children.remove(component);
}
@Override
public void operation() {
System.out.println("Composite " + name + " operation.");
for (Component child : children) {
child.operation();
}
}
}
// Example of using composition
class Client {
public static void main(String[] args) {
Composite root = new Composite("Root");
Composite branch1 = new Composite("Branch 1");
Leaf leaf1 = new Leaf("Leaf 1");
Leaf leaf2 = new Leaf("Leaf 2");
branch1.add(leaf1);
branch1.add(leaf2);
root.add(branch1);
Composite branch2 = new Composite("Branch 2");
Leaf leaf3 = new Leaf("Leaf 3");
branch2.add(leaf3);
root.add(branch2);
root.operation(); // Call operation on the root element, which propagates down
}
}