From 592bbea29e16b4695f29f6366e09c43d56e3c58a Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 11 Oct 2020 16:39:40 +0200 Subject: [PATCH] state_pattern_oop: Only allow change of contents in Draft state --- state_pattern_oop/src/main.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/state_pattern_oop/src/main.rs b/state_pattern_oop/src/main.rs index 0bb1e83..ea8c793 100644 --- a/state_pattern_oop/src/main.rs +++ b/state_pattern_oop/src/main.rs @@ -14,7 +14,9 @@ impl Post { } pub fn add_text(&mut self, text: &str) { - self.content.push_str(text); + if self.state.as_ref().unwrap().is_text_adjust_allowed() { + self.content.push_str(text); + } } pub fn content(&self) -> &str { @@ -42,6 +44,10 @@ trait State { fn content<'a>(&self, _post: &'a Post) -> &'a str { "" } + + fn is_text_adjust_allowed(&self) -> bool { + false + } } struct Draft {} @@ -58,6 +64,10 @@ impl State for Draft { fn reject(self: Box) -> Box { self } + + fn is_text_adjust_allowed(&self) -> bool { + true + } } struct PendingReview { @@ -119,6 +129,7 @@ fn main() { post.approve(); // Shouldn't cause approval to go forward! post.request_review(); + post.add_text("I ate a burger for lunch today"); //Shouldn't do anything assert_eq!("", post.content()); post.approve(); // First valid approval, we need two so the content should still be empty @@ -126,4 +137,7 @@ fn main() { post.approve(); // Last approval assert_eq!("I ate a salad for lunch today", post.content()); + + post.add_text("I ate nothing for lunch today"); //Shouldn't do anything + assert_eq!("I ate a salad for lunch today", post.content()); }