נבנה על ידיBuilt by Ariel Yohimovich
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).
חמשת עקרונות SOLID, ו-Strategy, Factory, Builder, Observer ו-Singleton (והבעיות שלו). בסוף המפגש מוסיפים צעד לפרויקט המלווה.The five SOLID principles, plus Strategy, Factory, Builder, Observer and Singleton (and its problems). At the end we add a step to the companion project.מה נעשה היום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
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגש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:
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושא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.)
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.)נושא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.
הבנאי של 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.נושא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).
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).נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder
בנו את 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].SOLID: חמישה עקרונות:SOLID: Five principles:
המונחים של המפגשThis session's termsStrategy: משפחת אלגוריתמים מאחורי interface אחד (Comparator, Discount).Strategy: A family of algorithms behind one interface (Comparator, Discount).
המונחים של המפגשThis session's termsFactory: מתודה (או מחלקה) שמחליטה איזה עצם ליצור לפי קלט, כך שהשאר לא תלוי במחלקות הקונקרטיות.Factory: A method (or class) deciding which object to create from some input, so the rest doesn't depend on the concrete classes.
המונחים של המפגשThis session's termsBuilder: בונים עצם צעד אחרי צעד:Builder: Build an object step by step:
המונחים של המפגשThis session's termsObserver: עצם שומר רשימת "מאזינים" ומודיע לכולם כשמשהו קורה.Observer: An object keeps a list of "listeners" and notifies them all when something happens.
המונחים של המפגשThis session's termsSingleton: מחלקה עם מופע יחיד לכל התוכנית (הכי פשוט:Singleton: A class with a single instance for the whole program (simplest:
המונחים של המפגשThis session's termsbooks.sort(...) לא יודע איך משווים.books.sort(...) doesn't know how to compare.
Strategy: סדר מיון כמחלקהStrategy: a sort order as a classכל אסטרטגיה היא מחלקה קטנה שמממשת Comparator, ומחליפים אותן בלי לגעת ברשימה.Each strategy is a small class implementing Comparator, and you swap them without touching the list.
Strategy: סדר מיון כמחלקהStrategy: a sort order as a class(במפגש 26 נכתוב את זה בשורה אחת עם למבדה.)(In session 26 we'll write it in one line with a lambda.)
Strategy: סדר מיון כמחלקהStrategy: a sort order as a classהבנאי של Book הוא private.Book's constructor is private.
Builder: הרבה שדות, קריאה ברורהBuilder: many fields, a clear callבונים דרך Book.Builder (מחלקה מקוננת static): כל מתודה מחזירה את ה-Builder עצמו, ולכן אפשר לשרשר.You build through Book.Builder (a static nested class): each method returns the Builder itself, so calls chain.
Builder: הרבה שדות, קריאה ברורהBuilder: many fields, a clear callמה שלא נקבע מקבל ברירת מחדל.Anything not set gets a default.
Builder: הרבה שדות, קריאה ברורהBuilder: many fields, a clear callShelf לא יודע מי מאזין ומה הוא עושה.Shelf doesn't know who listens or what they do.
Observer: להודיע לכל המאזיניםObserver: tell every listenerהוא רק עובר על הרשימה וקורא ל-bookAdded.It just goes over the list calling bookAdded.
Observer: להודיע לכל המאזיניםObserver: tell every listenerאפשר להוסיף מאזין חדש בלי לשנות את Shelf (ה-O ב-SOLID).You can add a new listener without changing Shelf (the O in SOLID).
Observer: להודיע לכל המאזיניםObserver: tell every listenerמדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמחלקה קוראת קובץ, מחשבת ממוצע, ושולחת מייל. איזה עיקרון נשבר?A class reads a file, computes an average, and sends an email. Which principle is broken?
- S: אחריות אחתS: single responsibility
- LL
- II
- אף אחדNone
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.S: אחריות אחתS: single responsibility
נכון: שלוש סיבות שונות להשתנות.Right: three different reasons to change.למה 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כדי שיהיה אפשר להחליף אותו, למשל במזויף בבדיקהSo it can be swapped, e.g. for a fake in a test
נכון: היפוך תלות.Right: dependency inversion.מה הבעיה העיקרית עם 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.הוא מצב גלובלי: כל קוד יכול לשנות אותו, וקשה לבדוק בבידודIt's global state: any code can change it, and it's hard to test in isolation
נכון.Right.Strategy: הנחותStrategy: discounts
interface Discount עם apply(double) ו-name().interface Discount with apply(double) and name().
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.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:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.Builder לפיצהA pizza Builder
Pizza עם בנאי private ו-Pizza.Builder(String size).Pizza with a private constructor and Pizza.Builder(String size).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.Observer למדחוםAn Observer for a thermometer
Thermometer מחזיק רשימת TempListener ומודיע לכולם ב-set.Thermometer keeps a list of TempListeners and notifies them all on set.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.היפוך תלות ומזויף לבדיקהDependency inversion and a test fake
Reminder מקבל Sender בבנאי ושולח please return <title>.Reminder takes a Sender in its constructor and sends please return <title>.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.Singleton עם enumA Singleton with an enum
enum Config { INSTANCE; } עם מפה פרטית, set ו-get (ברירת מחדל (none)).enum Config { INSTANCE; } with a private map, set and get (default (none)).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.Factory של אסטרטגיותA factory of strategies
Orders.byName(String) מחזירה Comparator<String>:Orders.byName(String) returns a Comparator<String>:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנו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
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.