2

These aren't the real classes but it's the best I can come up with that describes my struggle.

I'm using classes: Library, Book, Page.

The library class manages (adds/removes) all the books. The book class contains a collection of pages. The book may be open at any time and the book knows which page is currently active. The page class KNOWS when it has reached the end of the page, therefore, knowing when to turn to the next page. However, the turn page method is located in the Book class.

How can I accomplish this? How can the Page class communicate with the Book class? I feel like calling a method inside the Page class defeats the purpose. For example Page#turn would call Library#getBook#turnPage.

The page class is an abstract class because pages may be longer than a certain size and I am making it as flexible as possible for other people in the team to create pages and append them to a book:

Page Class
public abstract String getContent()
public abstract boolean hasReachedEnd()

What I've tried: At first, I switched Page to be an inner class of Book. However, I had to revert the change. Consider SuperLongPage extends Book.Page. I must create a Book class in order to create a page. The idea was scrapped but I really liked how I was able to call Book#turnPage.

I also tried to make them both dependencies of each other (not sure what this term is called). Book has pages and Page has the book it is part of. In this way, I was able to invoke the Book#turnPage but it felt like I cheated and didn't feel right. Am I right by doing this or should I not do this?

I also tried calling a method Page#endReached that took the parameter of a Book class. The method would check if it was a part of the book class and then it would call book#turnPage inside this method.

What are the other suggestions?

EDIT: I solved this issue by using the Observer pattern as noted by @buettner123 in the comments.

Kotori
  • 21
  • 3
  • 1
    Sounds like you could use the observer pattern here. Your page will notify all interested parties when it's reached the end and all subscribers (your book only in this case) can act upon. – buettner123 Sep 01 '20 at 05:19
  • Passing the Book instance to the Page constructor is an option. I do it all the time. No cheating there. I like @buettner123 suggestion though. Create a listener interface, make book implement it, add an `addListener` method to the page class, and register the book as a listener. You can also take a loo at [How to create custom Listeners in java?](https://stackoverflow.com/questions/6941321/how-to-create-custom-listeners-in-java) – Cardinal System Sep 01 '20 at 19:08

0 Answers0