Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main()
- {
- let mut post = Post::new();
- post.add_text("hello");
- assert_eq!("", post.content());
- post.request_review();
- assert_eq!("", post.content());
- post.approve();
- assert_eq!("hello", post.content());
- }
- struct Post {
- content: String,
- state: Option<Box<State>>,
- }
- impl Post {
- fn new() -> Post {
- Post {
- content: String::new(),
- state: Some(Box::new(Draft {}))
- }
- }
- fn content(&self) -> &str {
- self.state.as_ref().unwrap().content(&self)
- }
- fn add_text(&mut self, text: &str) {
- self.content.push_str(text);
- }
- 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())
- }
- }
- }
- trait State {
- fn request_review(self: Box<Self>) -> Box<State>;
- fn approve(self: Box<Self>) -> Box<State>;
- fn content<'a, 'b>(&'a self, _post: &'b Post) -> &'b str {
- ""
- }
- }
- struct Draft {}
- impl State for Draft {
- fn request_review(self: Box<Self>) -> Box<State> {
- Box::new(PendingReview {})
- }
- fn approve(self: Box<Self>) -> Box<State> {
- self
- }
- }
- struct PendingReview {}
- impl State for PendingReview {
- fn request_review(self: Box<Self>) -> Box<State> {
- self
- }
- fn approve(self: Box<Self>) -> Box<State> {
- Box::new(Published {})
- }
- }
- struct Published {}
- impl State for Published {
- fn request_review(self: Box<Self>) -> Box<State> {
- self
- }
- fn approve(self: Box<Self>) -> Box<State> {
- self
- }
- fn content<'a, 'b>(&'a self, post: &'b Post) -> &'b str {
- &post.content
- }
- }
Add Comment
Please, Sign In to add comment