This page looks best with JavaScript enabled

Decorate pattern

 ·  ☕ 2 min read  ·  ✍️ t1
+-------------------+ | Decorator | |-------------------| | - Define the | | interface for | | the decorator | | object | +-------------------+ +-------------------+ | Concrete Decorator| |-------------------| | - Implement the | | Decorator | | interface | | - Add additional | | behavior to | | the component | | object | +-------------------+

The Decorator pattern is a design pattern that allows developers to extend the functionality of an existing object dynamically without modifying the object’s structure. This is achieved by wrapping the original object with one or more decorator objects that add additional functionality to the original object.

The Decorator pattern is commonly used in real-world software development to add additional functionality to existing classes without modifying their structure. For example, a developer may want to add logging functionality to an existing class without modifying the class itself. This can be achieved by creating a decorator class that wraps the original class and adds the desired logging functionality.

Here is an example of the Decorator pattern in Rust:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// The base trait for all objects that can be decorated
trait Component {
    fn operation(&self);
}

// An implementation of the Component trait
struct ConcreteComponent {
    value: i32,
}

impl Component for ConcreteComponent {
    fn operation(&self) {
        println!("ConcreteComponent with value {}", self.value);
    }
}

// The Decorator trait
trait Decorator: Component {
    fn new(component: Box<dyn Component>) -> Self;
}

// A Decorator that adds logging functionality
struct LoggingDecorator {
    component: Box<dyn Component>,
}

impl Decorator for LoggingDecorator {
    fn new(component: Box<dyn Component>) -> Self {
        LoggingDecorator { component }
    }
}

impl Component for LoggingDecorator {
    fn operation(&self) {
        println!("Logging before operation");
        self.component.operation();
        println!("Logging after operation");
    }
}

fn main() {
    let component = ConcreteComponent { value: 42 };
    let decorated = LoggingDecorator::new(Box::new(component));
    decorated.operation();
}

In this example, the ConcreteComponent struct is the base object that can be decorated. The LoggingDecorator struct is a decorator that adds logging functionality to the ConcreteComponent. The operation method of the LoggingDecorator calls the operation method of the wrapped ConcreteComponent and logs the call before and after the call.

The Decorator pattern allows developers to add additional functionality to existing classes without modifying their structure, making it a useful pattern in real-world software development.

Share on

t1
WRITTEN BY
t1
Dev