Friend spotlight!
Whimsical Animations course
Friend spotlight!
NEW Whimsical Animations course
Friend spotlight! NEW Whimsical Animations course
huge discount only this week
Friend spotlight! Want to make your project stand out? NEW Whimsical Animations course huge discount only this week
装饰

Rust 装饰模式讲解和代码示例

装饰是一种结构设计模式 允许你通过将对象放入特殊封装对象中来为原对象增加新的行为

由于目标对象和装饰器遵循同一接口 因此你可用装饰来对对象进行无限次的封装 结果对象将获得所有封装器叠加而来的行为

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

装饰在其他编程语言中的实现

C# 装饰模式讲解和代码示例 C++ 装饰模式讲解和代码示例 Go 装饰模式讲解和代码示例 Java 装饰模式讲解和代码示例 PHP 装饰模式讲解和代码示例 Python 装饰模式讲解和代码示例 Ruby 装饰模式讲解和代码示例 Swift 装饰模式讲解和代码示例 TypeScript 装饰模式讲解和代码示例