春のセール
Prototype

Prototype を Rust で

Prototype 生成に関するデザインパターンの一つで 特定のクラスに結合することなく オブジェクト たとえ複雑なオブジェクトでも のクローン作成を可能とします

プロトタイプのクラス全部には 共通するインターフェースが必要です これにより 具象クラスが不明であってもオブジェクトを複製することが可能となります プロトタイプ・オブジェクトが 完全なコピーを生成できるのは 同じクラスのオブジェクト同士が非公開フィールドを互いにアクセスできるからです

Built-in Clone trait

Rust has a built-in std::clone::Clone trait with many implementations for various types (via #[derive(Clone)]). Thus, the Prototype pattern is ready to use out of the box.

main.rs

#[derive(Clone)]
struct Circle {
    pub x: u32,
    pub y: u32,
    pub radius: u32,
}

fn main() {
    let circle1 = Circle {
        x: 10,
        y: 15,
        radius: 10,
    };

    // Prototype in action.
    let mut circle2 = circle1.clone();
    circle2.radius = 77;

    println!("Circle 1: {}, {}, {}", circle1.x, circle1.y, circle1.radius);
    println!("Circle 2: {}, {}, {}", circle2.x, circle2.y, circle2.radius);
}

Output

Circle 1: 10, 15, 10
Circle 2: 10, 15, 77

他言語での Prototype

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