SOLID ותבניות עיצובSOLID & design patterns
חמשת עקרונות SOLID, ו-Strategy, Factory, Builder, Observer ו-Singleton (והבעיות שלו).
The five SOLID principles, plus Strategy, Factory, Builder, Observer and Singleton (and its problems).
Strategy: הנחותStrategy: discounts
תזכורת: מה ביקשוReminder: the task
interface Discount עם apply(double) ו-name(). שלושה מימושים: בלי הנחה, אחוזים, וסכום קבוע (לא מתחת ל-0). Checkout מקבל Discount בבנאי. עבור מחיר 100 הדפיסו none: 100.0, 10% off: 90.0, 15.0 off: 85.0.
interface Discount with apply(double) and name(). Three implementations: no discount, a percentage, and a fixed amount (never below 0). Checkout takes a Discount in its constructor. For a price of 100 print none: 100.0, 10% off: 90.0, 15.0 off: 85.0.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Discount[] options = {new NoDiscount(), new PercentOff(10), new FixedOff(15)};
for (Discount d : options) {
Checkout c = new Checkout(d);
System.out.println(d.name() + ": " + c.total(100));
}
}
}
interface Discount {
double apply(double price);
String name();
}
class NoDiscount implements Discount {
public double apply(double price) {
return price;
}
public String name() {
return "none";
}
}
class PercentOff implements Discount {
private final int percent;
PercentOff(int percent) {
this.percent = percent;
}
public double apply(double price) {
return price * (100 - percent) / 100;
}
public String name() {
return percent + "% off";
}
}
class FixedOff implements Discount {
private final double amount;
FixedOff(double amount) {
this.amount = amount;
}
public double apply(double price) {
return Math.max(0, price - amount);
}
public String name() {
return amount + " off";
}
}
class Checkout {
private final Discount discount;
Checkout(Discount discount) {
this.discount = discount;
}
double total(double price) {
return discount.apply(price);
}
}none: 100.0 10% off: 90.0 15.0 off: 85.0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Factory לצורותA shape factory
תזכורת: מה ביקשוReminder: the task
ShapeFactory.create(String kind, double size) מחזירה Circle או Square (records), וזורקת unknown shape: star (use circle or square) על סוג לא מוכר. הדפיסו 3.14, 9.0, ואת ההודעה.
ShapeFactory.create(String kind, double size) returns a Circle or a Square (records), and throws unknown shape: star (use circle or square) for an unknown kind. Print 3.14, 9.0, and the message.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
System.out.println(ShapeFactory.create("circle", 1).area());
System.out.println(ShapeFactory.create("square", 3).area());
try {
ShapeFactory.create("star", 2);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
interface Shape {
double area();
}
record Circle(double r) implements Shape {
public double area() {
return Math.round(Math.PI * r * r * 100) / 100.0;
}
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
}
class ShapeFactory {
static Shape create(String kind, double size) {
return switch (kind) {
case "circle" -> new Circle(size);
case "square" -> new Square(size);
default -> throw new IllegalArgumentException("unknown shape: " + kind + " (use circle or square)");
};
}
}3.14 9.0 unknown shape: star (use circle or square)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Builder לפיצהA pizza Builder
תזכורת: מה ביקשוReminder: the task
Pizza עם בנאי private ו-Pizza.Builder(String size). אופציונלי: cheese(boolean) (ברירת מחדל false) ו-topping(String) (ברירת מחדל plain). הדפיסו large +cheese olives ו-small plain.
Pizza with a private constructor and Pizza.Builder(String size). Optional: cheese(boolean) (default false) and topping(String) (default plain). Print large +cheese olives and small plain.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Pizza a = new Pizza.Builder("large").cheese(true).topping("olives").build();
Pizza b = new Pizza.Builder("small").build();
System.out.println(a);
System.out.println(b);
}
}
class Pizza {
private final String size;
private final boolean cheese;
private final String topping;
private Pizza(Builder b) {
size = b.size;
cheese = b.cheese;
topping = b.topping;
}
@Override
public String toString() {
return size + (cheese ? " +cheese" : "") + " " + topping;
}
static class Builder {
private final String size;
private boolean cheese = false;
private String topping = "plain";
Builder(String size) {
this.size = size;
}
Builder cheese(boolean c) {
cheese = c;
return this;
}
Builder topping(String t) {
topping = t;
return this;
}
Pizza build() {
return new Pizza(this);
}
}
}large +cheese olives small plain
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Observer למדחוםAn Observer for a thermometer
תזכורת: מה ביקשוReminder: the task
Thermometer מחזיק רשימת TempListener ומודיע לכולם ב-set. Display מדפיס תמיד (Display: 25C), Alarm(30) רק מעל 30 (ALARM: 32 > 30). קבעו 25 ואז 32.
Thermometer keeps a list of TempListeners and notifies them all on set. Display always prints (Display: 25C), Alarm(30) only above 30 (ALARM: 32 > 30). Set 25 then 32.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Thermometer t = new Thermometer();
t.subscribe(new Display());
t.subscribe(new Alarm(30));
t.set(25);
t.set(32);
}
}
interface TempListener {
void changed(int temp);
}
class Thermometer {
private final List<TempListener> listeners = new ArrayList<>();
void subscribe(TempListener l) {
listeners.add(l);
}
void set(int temp) {
for (TempListener l : listeners) {
l.changed(temp);
}
}
}
class Display implements TempListener {
public void changed(int temp) {
System.out.println("Display: " + temp + "C");
}
}
class Alarm implements TempListener {
private final int limit;
Alarm(int limit) {
this.limit = limit;
}
public void changed(int temp) {
if (temp > limit) {
System.out.println("ALARM: " + temp + " > " + limit);
}
}
}Display: 25C Display: 32C ALARM: 32 > 30
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
היפוך תלות ומזויף לבדיקהDependency inversion and a test fake
תזכורת: מה ביקשוReminder: the task
Reminder מקבל Sender בבנאי ושולח please return <title>. FakeSender רק שומר למי נשלח, ו-ConsoleSender מדפיס. עם המזויף שלחו ל-Noa ול-Avi והדפיסו [Noa, Avi], ואז עם ConsoleSender ל-Dana: to Dana: please return Ulysses.
Reminder takes a Sender in its constructor and sends please return <title>. FakeSender only records who it sent to, and ConsoleSender prints. With the fake, send to Noa and Avi and print [Noa, Avi], then with ConsoleSender to Dana: to Dana: please return Ulysses.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
FakeSender fake = new FakeSender();
Reminder r = new Reminder(fake);
r.remind("Noa", "Dune");
r.remind("Avi", "Emma");
System.out.println(fake.sent);
new Reminder(new ConsoleSender()).remind("Dana", "Ulysses");
}
}
interface Sender {
void send(String to, String text);
}
class ConsoleSender implements Sender {
public void send(String to, String text) {
System.out.println("to " + to + ": " + text);
}
}
class FakeSender implements Sender {
final List<String> sent = new ArrayList<>();
public void send(String to, String text) {
sent.add(to);
}
}
class Reminder {
private final Sender sender;
Reminder(Sender sender) {
this.sender = sender;
}
void remind(String person, String title) {
sender.send(person, "please return " + title);
}
}[Noa, Avi] to Dana: please return Ulysses
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder
תזכורת: מה ביקשוReminder: the task
בנו את 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].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
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<>();
books.add(new Book.Builder("Emma").year(1815).rating(4).build());
books.add(new Book.Builder("Dune").year(1965).rating(5).build());
books.add(new Book.Builder("Ulysses").year(1922).build());
for (Comparator<Book> order : List.of(new ByYear(), new ByRatingDesc())) {
books.sort(order);
System.out.println(books);
}
}
}
class Book {
private final String title;
private final int year;
private final int rating;
private Book(Builder b) {
title = b.title;
year = b.year;
rating = b.rating;
}
int year() {
return year;
}
int rating() {
return rating;
}
@Override
public String toString() {
return title;
}
static class Builder {
private final String title;
private int year = 0;
private int rating = 3;
Builder(String title) {
this.title = title;
}
Builder year(int y) {
year = y;
return this;
}
Builder rating(int r) {
rating = r;
return this;
}
Book build() {
return new Book(this);
}
}
}
class ByYear implements Comparator<Book> {
public int compare(Book a, Book b) {
return Integer.compare(a.year(), b.year());
}
}
class ByRatingDesc implements Comparator<Book> {
public int compare(Book a, Book b) {
return Integer.compare(b.rating(), a.rating());
}
}[Emma, Ulysses, Dune] [Dune, Emma, Ulysses]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Singleton עם enumA Singleton with an enum
תזכורת: מה ביקשוReminder: the task
enum Config { INSTANCE; } עם מפה פרטית, set ו-get (ברירת מחדל (none)). קבעו theme=dark דרך משתנה אחד וקראו דרך אחר. הדפיסו true dark (none). חשבו: מה יקרה בבדיקה שנייה שמניחה ש-theme ריק?
enum Config { INSTANCE; } with a private map, set and get (default (none)). Set theme=dark through one variable and read through another. Print true dark (none). Think: what happens in a second test that assumes theme is empty?
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Config a = Config.INSTANCE;
Config b = Config.INSTANCE;
a.set("theme", "dark");
System.out.println((a == b) + " " + b.get("theme") + " " + b.get("lang"));
}
}
enum Config {
INSTANCE;
private final java.util.Map<String, String> values = new java.util.HashMap<>();
void set(String key, String value) {
values.put(key, value);
}
String get(String key) {
return values.getOrDefault(key, "(none)");
}
}true dark (none)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Factory של אסטרטגיותA factory of strategies
תזכורת: מה ביקשוReminder: the task
Orders.byName(String) מחזירה Comparator<String>: alpha (לפי א-ב) או length (לפי אורך), ואחרת זורקת unknown order 'random', use: alpha, length. מיינו pear, fig, banana בשתי הדרכים והדפיסו alpha: [banana, fig, pear], length: [fig, pear, banana], ואת ההודעה.
Orders.byName(String) returns a Comparator<String>: alpha (alphabetical) or length (by length), otherwise it throws unknown order 'random', use: alpha, length. Sort pear, fig, banana both ways and print alpha: [banana, fig, pear], length: [fig, pear, banana], and the message.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("pear", "fig", "banana"));
for (String name : List.of("alpha", "length")) {
words.sort(Orders.byName(name));
System.out.println(name + ": " + words);
}
try {
Orders.byName("random");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
class Alphabetical implements Comparator<String> {
public int compare(String a, String b) {
return a.compareTo(b);
}
}
class ByLength implements Comparator<String> {
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
}
class Orders {
static Comparator<String> byName(String name) {
return switch (name) {
case "alpha" -> new Alphabetical();
case "length" -> new ByLength();
default -> throw new IllegalArgumentException("unknown order '" + name + "', use: alpha, length");
};
}
}alpha: [banana, fig, pear] length: [fig, pear, banana] unknown order 'random', use: alpha, length
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.