Guest User

Untitled

a guest
Jun 25th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. fn main()
  2. {
  3. let mut post = Post::new();
  4.  
  5. post.add_text("hello");
  6. assert_eq!("", post.content());
  7.  
  8. post.request_review();
  9. assert_eq!("", post.content());
  10.  
  11. post.approve();
  12. assert_eq!("hello", post.content());
  13. }
  14.  
  15. struct Post {
  16. content: String,
  17. state: Option<Box<State>>,
  18. }
  19.  
  20. impl Post {
  21. fn new() -> Post {
  22. Post {
  23. content: String::new(),
  24. state: Some(Box::new(Draft {}))
  25. }
  26. }
  27.  
  28. fn content(&self) -> &str {
  29. self.state.as_ref().unwrap().content(&self)
  30. }
  31.  
  32. fn add_text(&mut self, text: &str) {
  33. self.content.push_str(text);
  34. }
  35.  
  36. fn request_review(&mut self) {
  37. if let Some(s) = self.state.take() {
  38. self.state = Some(s.request_review())
  39. }
  40. }
  41.  
  42. fn approve(&mut self) {
  43. if let Some(s) = self.state.take() {
  44. self.state = Some(s.approve())
  45. }
  46. }
  47. }
  48.  
  49. trait State {
  50. fn request_review(self: Box<Self>) -> Box<State>;
  51. fn approve(self: Box<Self>) -> Box<State>;
  52. fn content<'a, 'b>(&'a self, _post: &'b Post) -> &'b str {
  53. ""
  54. }
  55. }
  56.  
  57. struct Draft {}
  58. impl State for Draft {
  59. fn request_review(self: Box<Self>) -> Box<State> {
  60. Box::new(PendingReview {})
  61. }
  62.  
  63. fn approve(self: Box<Self>) -> Box<State> {
  64. self
  65. }
  66. }
  67.  
  68. struct PendingReview {}
  69. impl State for PendingReview {
  70. fn request_review(self: Box<Self>) -> Box<State> {
  71. self
  72. }
  73.  
  74. fn approve(self: Box<Self>) -> Box<State> {
  75. Box::new(Published {})
  76. }
  77.  
  78. }
  79.  
  80. struct Published {}
  81. impl State for Published {
  82. fn request_review(self: Box<Self>) -> Box<State> {
  83. self
  84. }
  85.  
  86. fn approve(self: Box<Self>) -> Box<State> {
  87. self
  88. }
  89.  
  90. fn content<'a, 'b>(&'a self, post: &'b Post) -> &'b str {
  91. &post.content
  92. }
  93. }
Add Comment
Please, Sign In to add comment