From 4bd69ebbd83c5fa3b625dde28f8f170eb9e532ac Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 11 Oct 2020 16:42:00 +0200 Subject: [PATCH] Add state pattern: Types-way --- state_pattern_types/Cargo.toml | 9 ++++++ state_pattern_types/src/main.rs | 55 +++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 state_pattern_types/Cargo.toml create mode 100644 state_pattern_types/src/main.rs diff --git a/state_pattern_types/Cargo.toml b/state_pattern_types/Cargo.toml new file mode 100644 index 0000000..c66b710 --- /dev/null +++ b/state_pattern_types/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "state_pattern_types" +version = "0.1.0" +authors = ["laurens "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/state_pattern_types/src/main.rs b/state_pattern_types/src/main.rs new file mode 100644 index 0000000..14ed679 --- /dev/null +++ b/state_pattern_types/src/main.rs @@ -0,0 +1,55 @@ +pub struct DraftPost { + content: String, +} + +pub struct PendingReviewPost { + content: String, +} + +pub struct Post { + content: String, +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + + let post = post.request_review(); + + let post = post.approve(); + + assert_eq!("I ate a salad for lunch today", post.content()); +}