УРОК 13 ИЗ 16
Паттерны проектирования
2 Теория
Зачем
Паттерны — проверенные решения типичных задач проектирования. Они дают общий язык: «здесь Фабрика», «тут Стратегия».
Singleton — один экземпляр
public enum Config {
INSTANCE;
private final Properties props = new Properties();
public String get(String key) { return props.getProperty(key); }
}
Используйте осторожно: глобальное состояние затрудняет тесты.
Factory — создание объектов
interface Notifier { void send(String msg); }
class Email implements Notifier { public void send(String m) { System.out.println("email: " + m); } }
class Sms implements Notifier { public void send(String m) { System.out.println("sms: " + m); } }
class NotifierFactory {
static Notifier create(String type) {
return switch (type) {
case "email" -> new Email();
case "sms" -> new Sms();
default -> throw new IllegalArgumentException(type);
};
}
}
Strategy — взаимозаменяемые алгоритмы
interface Discount { double apply(double price); }
record Percent(double p) implements Discount { public double apply(double x) { return x * (1 - p / 100); } }
record Fixed(double v) implements Discount { public double apply(double x) { return Math.max(0, x - v); } }
double total = new Percent(10).apply(200); // 180
Observer — подписка на события
class EventBus {
private final List<Consumer<String>> subs = new ArrayList<>();
void subscribe(Consumer<String> s) { subs.add(s); }
void publish(String e) { subs.forEach(s -> s.accept(e)); }
}
Builder — сложные объекты
User u = User.builder().name("Аня").age(17).email("a@b.c").build();
Паттерн — не цель, а инструмент: не применяйте его, если задача решается проще.
