נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
24
חלקPart 4: OOP מתקדםAdvanced OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

SOLID ותבניות עיצובSOLID & design patterns

חמשת עקרונות SOLID, ו-Strategy, Factory, Builder, Observer ו-Singleton (והבעיות שלו).

The five SOLID principles, plus Strategy, Factory, Builder, Observer and Singleton (and its problems).

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • SOLID: חמישה עקרונות: S – אחריות אחת למחלקה; O – פתוח להרחבה, סגור לשינוי; L – תת-מחלקה עובדת בכל מקום שההורה עובד; I – interfaces קטנים וממוקדים; D – תלות ב-interfaces, לא במימושים.SOLID: Five principles: S – one job per class; O – open to extension, closed to change; L – a subclass works wherever the parent works; I – small, focused interfaces; D – depend on interfaces, not implementations.
  • Strategy: משפחת אלגוריתמים מאחורי interface אחד (Comparator, Discount). מי שמשתמש מקבל אסטרטגיה ולא יודע איזו.Strategy: A family of algorithms behind one interface (Comparator, Discount). The user gets a strategy and doesn't know which one.
  • Factory: מתודה (או מחלקה) שמחליטה איזה עצם ליצור לפי קלט, כך שהשאר לא תלוי במחלקות הקונקרטיות.Factory: A method (or class) deciding which object to create from some input, so the rest doesn't depend on the concrete classes.
  • Builder: בונים עצם צעד אחרי צעד: new Book.Builder("Dune").year(1965).build(). נוח כשיש הרבה שדות אופציונליים, במקום בנאים עם עשרה פרמטרים.Builder: Build an object step by step: new Book.Builder("Dune").year(1965).build(). Handy with many optional fields, instead of constructors with ten parameters.
  • Observer: עצם שומר רשימת "מאזינים" ומודיע לכולם כשמשהו קורה. המאזינים לא תלויים זה בזה.Observer: An object keeps a list of "listeners" and notifies them all when something happens. The listeners don't depend on each other.
  • Singleton: מחלקה עם מופע יחיד לכל התוכנית (הכי פשוט: enum עם ערך אחד). הבעיה: זה מצב גלובלי, וקשה לבדוק ולהחליף אותו.Singleton: A class with a single instance for the whole program (simplest: an enum with one value). The problem: it's global state, hard to test and to swap.
  • היפוך תלות: מחלקה מקבלת את מה שהיא צריכה מבחוץ, כ-interface (Reminder(Sender sender)), במקום ליצור אותו בעצמה. כך בבדיקה מעבירים מימוש מזויף.dependency inversion: A class receives what it needs from outside, as an interface (Reminder(Sender sender)), instead of creating it itself. In a test you then pass a fake.

02Strategy: סדר מיון כמחלקהStrategy: a sort order as a class

books.sort(...) לא יודע איך משווים. כל אסטרטגיה היא מחלקה קטנה שמממשת Comparator, ומחליפים אותן בלי לגעת ברשימה. (במפגש 26 נכתוב את זה בשורה אחת עם למבדה.)

books.sort(...) doesn't know how to compare. Each strategy is a small class implementing Comparator, and you swap them without touching the list. (In session 26 we'll write it in one line with a lambda.)

Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Book> books = new ArrayList<>(List.of(new Book("Emma", 1815), new Book("Dune", 1965), new Book("Ulysses", 1922)));
        books.sort(new ByTitle());
        System.out.println(books);
        books.sort(new ByYear());
        System.out.println(books);
    }
}

record Book(String title, int year) {
    @Override
    public String toString() {
        return title + " " + year;
    }
}

class ByTitle implements Comparator<Book> {
    @Override
    public int compare(Book a, Book b) {
        return a.title().compareTo(b.title());
    }
}

class ByYear implements Comparator<Book> {
    @Override
    public int compare(Book a, Book b) {
        return Integer.compare(a.year(), b.year());
    }
}
פלטOutput
[Dune 1965, Emma 1815, Ulysses 1922]
[Emma 1815, Ulysses 1922, Dune 1965]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03Builder: הרבה שדות, קריאה ברורהBuilder: many fields, a clear call

הבנאי של Book הוא private. בונים דרך Book.Builder (מחלקה מקוננת static): כל מתודה מחזירה את ה-Builder עצמו, ולכן אפשר לשרשר. מה שלא נקבע מקבל ברירת מחדל.

Book's constructor is private. You build through Book.Builder (a static nested class): each method returns the Builder itself, so calls chain. Anything not set gets a default.

Main.java
public class Main {
    public static void main(String[] args) {
        Book b = new Book.Builder("Dune").author("Herbert").year(1965).rating(5).build();
        Book c = new Book.Builder("Notes").build();
        System.out.println(b);
        System.out.println(c);
    }
}

class Book {
    private final String title;
    private final String author;
    private final int year;
    private final int rating;

    private Book(Builder b) {
        this.title = b.title;
        this.author = b.author;
        this.year = b.year;
        this.rating = b.rating;
    }

    @Override
    public String toString() {
        return title + " by " + author + " (" + year + ") " + rating + "/5";
    }

    static class Builder {
        private final String title;
        private String author = "unknown";
        private int year = 0;
        private int rating = 3;

        Builder(String title) {
            this.title = title;
        }

        Builder author(String a) {
            author = a;
            return this;
        }

        Builder year(int y) {
            year = y;
            return this;
        }

        Builder rating(int r) {
            rating = r;
            return this;
        }

        Book build() {
            return new Book(this);
        }
    }
}
פלטOutput
Dune by Herbert (1965) 5/5
Notes by unknown (0) 3/5
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04Observer: להודיע לכל המאזיניםObserver: tell every listener

Shelf לא יודע מי מאזין ומה הוא עושה. הוא רק עובר על הרשימה וקורא ל-bookAdded. אפשר להוסיף מאזין חדש בלי לשנות את Shelf (ה-O ב-SOLID).

Shelf doesn't know who listens or what they do. It just goes over the list calling bookAdded. You can add a new listener without changing Shelf (the O in SOLID).

Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Shelf shelf = new Shelf();
        shelf.subscribe(new Logger());
        shelf.subscribe(new Counter());
        shelf.add("Dune");
        shelf.add("Emma");
    }
}

interface ShelfListener {
    void bookAdded(String title, int size);
}

class Shelf {
    private final List<String> books = new ArrayList<>();
    private final List<ShelfListener> listeners = new ArrayList<>();

    void subscribe(ShelfListener l) {
        listeners.add(l);
    }

    void add(String title) {
        books.add(title);
        for (ShelfListener l : listeners) {
            l.bookAdded(title, books.size());
        }
    }
}

class Logger implements ShelfListener {
    public void bookAdded(String title, int size) {
        System.out.println("log: added " + title);
    }
}

class Counter implements ShelfListener {
    public void bookAdded(String title, int size) {
        System.out.println("count: " + size);
    }
}
פלטOutput
log: added Dune
count: 1
log: added Emma
count: 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05הצעד של היום בפרויקט מדףToday's step in the Shelf project

בנו את Emma (1815, 4), Dune (1965, 5) ו-Ulysses (1922, דירוג ברירת מחדל 3) עם Book.Builder. מיינו לפי שנה (ByYear) ואז לפי דירוג יורד (ByRatingDesc), והדפיסו [Emma, Ulysses, Dune] ו-[Dune, Emma, Ulysses].

Build Emma (1815, 4), Dune (1965, 5) and Ulysses (1922, default rating 3) with Book.Builder. Sort by year (ByYear) then by rating descending (ByRatingDesc), and print [Emma, Ulysses, Dune] and [Dune, Emma, Ulysses].

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich