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 原型模式讲解和代码示例

原型是一种创建型设计模式 使你能够复制对象 甚至是复杂对象 而又无需使代码依赖它们所属的类

所有的原型类都必须有一个通用的接口 使得即使在对象所属的具体类未知的情况下也能复制对象 原型对象可以生成自身的完整副本 因为相同类的对象可以相互访问对方的私有成员变量

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

原型在其他编程语言中的实现

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