![Prototype](/images/patterns/cards/prototype-mini.png?id=bc3046bb39ff36574c08d49839fd1c8e)
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