-
Notifications
You must be signed in to change notification settings - Fork 110
/
state.rs
94 lines (83 loc) · 2.38 KB
/
state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//! State is a behavioral design pattern that lets an object alter its behavior when its internal state changes.
//! It appears as if the object changed its class.
//! We’ll implement a blog post workflow
//! 1. A blog post starts as an empty draft.
//! 2. When the draft is done, a review of the post is requested.
//! 3. When the post is approved, it gets published.
//! 4. Only published blog posts return content to print, so unapproved posts can’t accidentally be published.
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn content<'a>(&self, _post: &'a Post) -> &'a str {
""
}
}
struct Draft;
impl State for Draft {
fn request_review(self: Box<Draft>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Draft>) -> Box<dyn State> {
self
}
}
struct PendingReview;
impl State for PendingReview {
fn request_review(self: Box<PendingReview>) -> Box<dyn State> {
self
}
fn approve(self: Box<PendingReview>) -> Box<dyn State> {
Box::new(Published {})
}
}
struct Published;
impl State for Published {
fn request_review(self: Box<Published>) -> Box<dyn State> {
self
}
fn approve(self: Box<Published>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
}
struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
fn content(&self) -> &str {
self.state.as_ref().unwrap().content(self)
}
fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
fn main() {
let mut post = Post::new();
let text = "State is a behavioral design pattern.";
post.add_text(text);
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!(text, post.content());
println!("post content: {}", post.content());
}