fork download
  1. "--- Class Definition: Book ---"
  2. Object subclass: Book [
  3. | title isBorrowed |
  4.  
  5. Book class >> newWithTitle: aString [
  6. ^ (super new) initializeWithTitle: aString
  7. ]
  8.  
  9. initializeWithTitle: aString [
  10. title := aString.
  11. isBorrowed := false.
  12. ]
  13.  
  14. title [ ^ title ]
  15. isBorrowed [ ^ isBorrowed ]
  16.  
  17. borrowBook [
  18. isBorrowed ifTrue: [ ^ false ]. "Already borrowed"
  19. isBorrowed := true.
  20. ^ true.
  21. ]
  22.  
  23. returnBook [
  24. isBorrowed ifFalse: [ ^ false ]. "Already returned"
  25. isBorrowed := false.
  26. ^ true.
  27. ]
  28. ]
  29.  
  30. "--- Class Definition: User ---"
  31. Object subclass: User [
  32. | name |
  33.  
  34. User class >> newWithName: aString [
  35. ^ (super new) initializeWithName: aString
  36. ]
  37.  
  38. initializeWithName: aString [
  39. name := aString.
  40. ]
  41.  
  42. name [ ^ name ]
  43.  
  44. borrow: aBook [
  45. Transcript show: name; show: ' tries to borrow "'; show: aBook title; show: '"... '.
  46. (aBook borrowBook)
  47. ifTrue: [ Transcript show: 'Success!'; cr ]
  48. ifFalse: [ Transcript show: 'Failed (Already borrowed).'; cr ].
  49. ]
  50.  
  51. return: aBook [
  52. Transcript show: name; show: ' returns "'; show: aBook title; show: '"... '.
  53. (aBook returnBook)
  54. ifTrue: [ Transcript show: 'Success!'; cr ]
  55. ifFalse: [ Transcript show: 'Failed (Not borrowed).'; cr ].
  56. ]
  57. ]
  58.  
  59. "--- Main Simulation Script ---"
  60. | book1 book2 studentA studentB |
  61.  
  62. "1. Create instances (Objects)"
  63. book1 := Book newWithTitle: 'Smalltalk-80 Practice'.
  64. book2 := Book newWithTitle: 'Introduction to AI 2026'.
  65. studentA := User newWithName: 'Taro'.
  66. studentB := User newWithName: 'Hanako'.
  67.  
  68. Transcript show: '=== Library System Simulation ==='; cr; cr.
  69.  
  70. "2. Student A borrows Book 1"
  71. studentA borrow: book1.
  72.  
  73. "3. Student B tries to borrow the same Book 1 (Should fail)"
  74. studentB borrow: book1.
  75.  
  76. "4. Student B borrows Book 2"
  77. studentB borrow: book2.
  78.  
  79. "5. Student A returns Book 1"
  80. studentA return: book1.
  81.  
  82. "6. Student B tries to borrow Book 1 again (Should succeed now)"
  83. studentB borrow: book1.
Success #stdin #stdout 0.01s 8688KB
stdin
Standard input is empty
stdout
=== Library System Simulation ===

Taro tries to borrow "Smalltalk-80 Practice"... Success!
Hanako tries to borrow "Smalltalk-80 Practice"... Failed (Already borrowed).
Hanako tries to borrow "Introduction to AI 2026"... Success!
Taro returns "Smalltalk-80 Practice"... Success!
Hanako tries to borrow "Smalltalk-80 Practice"... Success!