春のセール
Decorator

Decorator を Rust で

Decorator 構造に関するパターンのひとつで オブジェクトをと呼ばれる特別なラッパー・オブジェクト内に配置することにより 新しい振る舞いを動的に追加できます

対象のオブジェクトとデコレーターは同じインターフェースに従うため デコレーターを使うと オブジェクトを何重にも包み込むことができます その結果として生成されるオブジェクトは 全部のラッパーの振る舞いを集積した振る舞いをします

Input streams decoration

There is a practical example in Rust's standard library for input/output operations.

A buffered reader decorates a vector reader adding buffered behavior.

let mut input = BufReader::new(Cursor::new("Input data"));
input.read(&mut buf).ok();

main.rs

use std::io::{BufReader, Cursor, Read};

fn main() {
    let mut buf = [0u8; 10];

    // A buffered reader decorates a vector reader which wraps input data.
    let mut input = BufReader::new(Cursor::new("Input data"));

    input.read(&mut buf).ok();

    print!("Read from a buffered reader: ");

    for byte in buf {
        print!("{}", char::from(byte));
    }

    println!();
}

Output

Read from a buffered reader: Input data

他言語での Decorator

Decorator を C# で Decorator を C++ で Decorator を Go で Decorator を Java で Decorator を PHP で Decorator を Python で Decorator を Ruby で Decorator を Swift で Decorator を TypeScript で