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

חזרה למפגשBack
JavaJava

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

מפגש 24: חמשת עקרונות SOLID, ו-Strategy, Factory, Builder, Observer ו-Singleton (והבעיות שלו).Session 24: The five SOLID principles, plus Strategy, Factory, Builder, Observer and Singleton (and its problems).

מה נעשה היוםToday's plan

  • מונחיםTerms
  • Strategy: סדר מיון כמחלקהStrategy: a sort order as a class
  • Builder: הרבה שדות, קריאה ברורהBuilder: many fields, a clear call
  • Observer: להודיע לכל המאזיניםObserver: tell every listener
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

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

  • SOLID: חמישה עקרונות:SOLID: Five principles:
  • Strategy: משפחת אלגוריתמים מאחורי interface אחד (Comparator, Discount).Strategy: A family of algorithms behind one interface (Comparator, Discount).
  • 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: בונים עצם צעד אחרי צעד:Builder: Build an object step by step:
  • Observer: עצם שומר רשימת "מאזינים" ומודיע לכולם כשמשהו קורה.Observer: An object keeps a list of "listeners" and notifies them all when something happens.
  • Singleton: מחלקה עם מופע יחיד לכל התוכנית (הכי פשוט:Singleton: A class with a single instance for the whole program (simplest:
נושאTopic 2

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

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

  • books.sort(...) לא יודע איך משווים.books.sort(...) doesn't know how to compare.
  • כל אסטרטגיה היא מחלקה קטנה שמממשת Comparator, ומחליפים אותן בלי לגעת ברשימה.Each strategy is a small class implementing Comparator, and you swap them without touching the list.
  • (במפגש 26 נכתוב את זה בשורה אחת עם למבדה.)(In session 26 we'll write it in one line with a lambda.)
נושאTopic 3

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

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

  • הבנאי של Book הוא private.Book's constructor is private.
  • בונים דרך Book.Builder (מחלקה מקוננת static): כל מתודה מחזירה את ה-Builder עצמו, ולכן אפשר לשרשר.You build through Book.Builder (a static nested class): each method returns the Builder itself, so calls chain.
  • מה שלא נקבע מקבל ברירת מחדל.Anything not set gets a default.
נושאTopic 4

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

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

  • Shelf לא יודע מי מאזין ומה הוא עושה.Shelf doesn't know who listens or what they do.
  • הוא רק עובר על הרשימה וקורא ל-bookAdded.It just goes over the list calling bookAdded.
  • אפשר להוסיף מאזין חדש בלי לשנות את Shelf (ה-O ב-SOLID).You can add a new listener without changing Shelf (the O in SOLID).
נושאTopic 5

פרויקט מדףShelf project

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

  • מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder

SOLID: חמישה עקרונות:SOLID: Five principles:

Strategy: משפחת אלגוריתמים מאחורי interface אחד (Comparator, Discount).Strategy: A family of algorithms behind one interface (Comparator, Discount).

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: בונים עצם צעד אחרי צעד:Builder: Build an object step by step:

Observer: עצם שומר רשימת "מאזינים" ומודיע לכולם כשמשהו קורה.Observer: An object keeps a list of "listeners" and notifies them all when something happens.

Singleton: מחלקה עם מופע יחיד לכל התוכנית (הכי פשוט:Singleton: A class with a single instance for the whole program (simplest:

books.sort(...) לא יודע איך משווים.books.sort(...) doesn't know how to compare.

כל אסטרטגיה היא מחלקה קטנה שמממשת Comparator, ומחליפים אותן בלי לגעת ברשימה.Each strategy is a small class implementing Comparator, and you swap them without touching the list.

(במפגש 26 נכתוב את זה בשורה אחת עם למבדה.)(In session 26 we'll write it in one line with a lambda.)

הבנאי של Book הוא private.Book's constructor is private.

בונים דרך Book.Builder (מחלקה מקוננת static): כל מתודה מחזירה את ה-Builder עצמו, ולכן אפשר לשרשר.You build through Book.Builder (a static nested class): each method returns the Builder itself, so calls chain.

מה שלא נקבע מקבל ברירת מחדל.Anything not set gets a default.

Shelf לא יודע מי מאזין ומה הוא עושה.Shelf doesn't know who listens or what they do.

הוא רק עובר על הרשימה וקורא ל-bookAdded.It just goes over the list calling bookAdded.

אפשר להוסיף מאזין חדש בלי לשנות את Shelf (ה-O ב-SOLID).You can add a new listener without changing Shelf (the O in SOLID).

מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder

מחלקה קוראת קובץ, מחשבת ממוצע, ושולחת מייל. איזה עיקרון נשבר?A class reads a file, computes an average, and sends an email. Which principle is broken?

  • S: אחריות אחתS: single responsibility
  • LL
  • II
  • אף אחדNone

S: אחריות אחתS: single responsibility

למה Reminder מקבל Sender בבנאי במקום ליצור new EmailSender() בעצמו?Why does Reminder take a Sender in its constructor instead of creating new EmailSender() itself?

  • כדי שיהיה אפשר להחליף אותו, למשל במזויף בבדיקהSo it can be swapped, e.g. for a fake in a test
  • כי זה מהיר יותרBecause it's faster
  • כי Java דורשתBecause Java requires it
  • אין סיבהNo reason

כדי שיהיה אפשר להחליף אותו, למשל במזויף בבדיקהSo it can be swapped, e.g. for a fake in a test

מה הבעיה העיקרית עם Singleton?What's the main problem with Singleton?

  • הוא איטיIt's slow
  • הוא מצב גלובלי: כל קוד יכול לשנות אותו, וקשה לבדוק בבידודIt's global state: any code can change it, and it's hard to test in isolation
  • אי אפשר לכתוב אותו ב-JavaYou can't write one in Java
  • הוא תופס הרבה זיכרוןIt uses a lot of memory

הוא מצב גלובלי: כל קוד יכול לשנות אותו, וקשה לבדוק בבידודIt's global state: any code can change it, and it's hard to test in isolation

Strategy: הנחותStrategy: discounts

  • interface Discount עם apply(double) ו-name().interface Discount with apply(double) and name().

Factory לצורותA shape factory

  • ShapeFactory.create(String kind, double size) מחזירה Circle או Square (records), וזורקת `unknown shape:ShapeFactory.create(String kind, double size) returns a Circle or a Square (records), and throws `unknown shape:

Builder לפיצהA pizza Builder

  • Pizza עם בנאי private ו-Pizza.Builder(String size).Pizza with a private constructor and Pizza.Builder(String size).

Observer למדחוםAn Observer for a thermometer

  • Thermometer מחזיק רשימת TempListener ומודיע לכולם ב-set.Thermometer keeps a list of TempListeners and notifies them all on set.

היפוך תלות ומזויף לבדיקהDependency inversion and a test fake

  • Reminder מקבל Sender בבנאי ושולח please return <title>.Reminder takes a Sender in its constructor and sends please return <title>.

מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder

  • בנו את Emma (1815, 4), Dune (1965, 5) ו-Ulysses (1922, דירוג ברירת מחדל 3) עם Book.Builder.Build Emma (1815, 4), Dune (1965, 5) and Ulysses (1922, default rating 3) with Book.Builder.

Singleton עם enumA Singleton with an enum

  • enum Config { INSTANCE; } עם מפה פרטית, set ו-get (ברירת מחדל (none)).enum Config { INSTANCE; } with a private map, set and get (default (none)).

Factory של אסטרטגיותA factory of strategies

  • Orders.byName(String) מחזירה Comparator<String>:Orders.byName(String) returns a Comparator<String>:

מה למדנוWhat we learned

  • SOLID: חמישה עקרונות:SOLID: Five principles:
  • books.sort(...) לא יודע איך משווים.books.sort(...) doesn't know how to compare.
  • הבנאי של Book הוא private.Book's constructor is private.
  • Shelf לא יודע מי מאזין ומה הוא עושה.Shelf doesn't know who listens or what they do.
  • מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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