|
| 1 | +pub struct Post { |
| 2 | + content: String, |
| 3 | + state: Option<Box<dyn State>>, |
| 4 | +} |
| 5 | + |
| 6 | +impl Post { |
| 7 | + pub fn new() -> Post { |
| 8 | + Post { |
| 9 | + content: String::new(), |
| 10 | + state: Some(Box::new(Draft {})), |
| 11 | + } |
| 12 | + } |
| 13 | + pub fn add_text(&mut self, text: &str) { |
| 14 | + self.content.push_str(text); |
| 15 | + } |
| 16 | + pub fn content(&self) -> &str { |
| 17 | + self.state.as_ref().unwrap().content(self) |
| 18 | + } |
| 19 | + pub fn request_review(&mut self) { |
| 20 | + if let Some(state) = self.state.take() { |
| 21 | + self.state = Some(state.request_review()); |
| 22 | + } |
| 23 | + } |
| 24 | + pub fn approve(&mut self) { |
| 25 | + if let Some(state) = self.state.take() { |
| 26 | + self.state = Some(state.approve()); |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +trait State { |
| 32 | + fn request_review(self: Box<Self>) -> Box<dyn State>; |
| 33 | + fn approve(self: Box<Self>) -> Box<dyn State>; |
| 34 | + fn content<'a>(&self, _post: &'a Post) -> &'a str { |
| 35 | + "" |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +struct Draft {} |
| 40 | + |
| 41 | +impl State for Draft { |
| 42 | + fn request_review(self: Box<Self>) -> Box<dyn State> { |
| 43 | + Box::new(PendingReview {}) |
| 44 | + } |
| 45 | + fn approve(self: Box<Self>) -> Box<dyn State> { |
| 46 | + self |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +struct PendingReview {} |
| 51 | + |
| 52 | +impl State for PendingReview { |
| 53 | + fn request_review(self: Box<Self>) -> Box<dyn State> { |
| 54 | + self |
| 55 | + } |
| 56 | + fn approve(self: Box<Self>) -> Box<dyn State> { |
| 57 | + Box::new(Published {}) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +struct Published {} |
| 62 | + |
| 63 | +impl State for Published { |
| 64 | + fn request_review(self: Box<Self>) -> Box<dyn State> { |
| 65 | + self |
| 66 | + } |
| 67 | + fn approve(self: Box<Self>) -> Box<dyn State> { |
| 68 | + self |
| 69 | + } |
| 70 | + fn content<'a>(&self, post: &'a Post) -> &'a str { |
| 71 | + &post.content |
| 72 | + } |
| 73 | +} |
0 commit comments