Add state pattern: Types-way
This commit is contained in:
parent
592bbea29e
commit
4bd69ebbd8
2 changed files with 64 additions and 0 deletions
9
state_pattern_types/Cargo.toml
Normal file
9
state_pattern_types/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
[package]
|
||||||
|
name = "state_pattern_types"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["laurens <miers132@gmail.com>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
55
state_pattern_types/src/main.rs
Normal file
55
state_pattern_types/src/main.rs
Normal file
|
|
@ -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());
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue