How to handle various operations defined during the execution of an object (s)

I am having design problems in my project and I hope to get some help. I came up with an example that I think describes the problem I am facing. I'm new to software development, so forgive me if I completely missed something.

This example says that I have:

struct Book {
    std::string author_first_name;
    std::string author_last_name;
    int year_published;
    double price_in_dollars;
 };

class BookCase {
    std::vector<Book> all_books;
    // Rest of class implementation
 }

I read in all books from a file or more than one file and save them in BookCase. Then I want to do a bunch of BookCase operations defined at runtime, and that's where I got stuck.

Say that the user wants to sort books by author and then export, next time sort by name or price, or wants to add a new operation, perhaps delete books published before year X.

:

  • . BookCase:

    class BookCase {
    
        void SortByLastNameAscending();
        void SortByLastNameDescending();
        void SortByPriceAscending();
     // etc...};
    

    , , , , , . - "BookCaseProcessor", . - , , , .

  • -. , RemoveBooksBeforeYear(), RemoveBooksThatCostLessThan(), SortByLastNameDescending(). , , , 10 . , , if.

+4
3

, - std:: function.

, :

void SortByLastNameAscending(BookCase&) {...}
void SortByLastNameDescending(BookCase&) {...}
void SortByPriceAscending(BookCase&) {...}

:

std::vector<std::function<void(BookCase&)>> pipeline;

//populate the pipeline
if(user_choice == "sort") {
  pipeline.emplace_back(SortByLastNameAscending);
}

:

BookCase data;
for(auto& op : pipeline) {
  op(data);
}
+1

- . .

, BookCase. , ! Processor - . Processor , , , BookCase.

, , SortBy<Field>..., - , , , . , " ". , "/" .

+1

, , BookCase. , . , , .

You are actually dealing with BookSelection. (Depending on what you want to do, you still need to save BookCase, or the file may be a bookcase.)

In addition, since the focus is on sorting and modification, it listmay make more sense than vectors.

0
source

Source: https://habr.com/ru/post/1667026/


All Articles