← Назад к вопросам

Какие знаешь группы GoF паттернов?

2.0 Middle🔥 161 комментариев
#SOLID и паттерны проектирования

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Группы GoF (Gang of Four) паттернов в Java

GoF паттерны - это 23 классических паттерна проектирования, описанные в книге "Design Patterns: Elements of Reusable Object-Oriented Software". Все они разделены на три группы.

1. CREATIONAL Паттерны (Порождающие)

Отвечают за создание объектов и инкапсуляцию процесса создания.

Singleton - один экземпляр класса на всё приложение:

public class DatabaseConnection {
    private static volatile DatabaseConnection instance;
    
    private DatabaseConnection() {}
    
    public static DatabaseConnection getInstance() {
        if (instance == null) {
            synchronized (DatabaseConnection.class) {
                if (instance == null) {
                    instance = new DatabaseConnection();
                }
            }
        }
        return instance;
    }
}

Factory Method - создание объектов без указания точных классов:

public abstract class Animal {
    public abstract void speak();
}

public class Dog extends Animal {
    public void speak() { System.out.println("Woof!"); }
}

public class AnimalFactory {
    public static Animal createAnimal(String type) {
        if ("dog".equals(type)) return new Dog();
        if ("cat".equals(type)) return new Cat();
        throw new IllegalArgumentException("Unknown type");
    }
}

Abstract Factory - создание семейств связанных объектов:

public interface UIFactory {
    Button createButton();
    Checkbox createCheckbox();
}

public class WindowsUIFactory implements UIFactory {
    public Button createButton() { return new WindowsButton(); }
    public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}

public class MacUIFactory implements UIFactory {
    public Button createButton() { return new MacButton(); }
    public Checkbox createCheckbox() { return new MacCheckbox(); }
}

Builder - пошаговое построение сложного объекта:

public class User {
    private String name;
    private String email;
    private Integer age;
    
    public static Builder builder() { return new Builder(); }
    
    public static class Builder {
        private String name;
        private String email;
        private Integer age;
        
        public Builder name(String name) { this.name = name; return this; }
        public Builder email(String email) { this.email = email; return this; }
        public Builder age(Integer age) { this.age = age; return this; }
        
        public User build() { return new User(this); }
    }
}

// Использование
User user = User.builder()
    .name("John")
    .email("john@example.com")
    .age(30)
    .build();

Prototype - копирование объектов вместо создания новых:

public class Shape implements Cloneable {
    private String color;
    
    public Shape clone() throws CloneNotSupportedException {
        return (Shape) super.clone();
    }
}

2. STRUCTURAL Паттерны (Структурные)

Отвечают за композицию классов и объектов в более крупные структуры.

Adapter - адаптация интерфейса несовместимых классов:

// Старый интерфейс
public interface LegacyPaymentSystem {
    void pay(double amount);
}

// Новый интерфейс
public interface ModernPaymentGateway {
    void processPayment(BigDecimal amount);
}

// Адаптер
public class PaymentAdapter implements ModernPaymentGateway {
    private LegacyPaymentSystem legacySystem;
    
    public void processPayment(BigDecimal amount) {
        legacySystem.pay(amount.doubleValue());
    }
}

Decorator - добавление функционала к объектам динамически:

public abstract class Coffee {
    public abstract double getCost();
}

public class SimpleCoffee extends Coffee {
    public double getCost() { return 2.0; }
}

public abstract class CoffeeDecorator extends Coffee {
    protected Coffee coffee;
    public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; }
}

public class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) { super(coffee); }
    public double getCost() { return coffee.getCost() + 0.5; }
}

// Использование
Coffee coffee = new MilkDecorator(new SimpleCoffee());

Facade - упрощённый интерфейс к сложной подсистеме:

public class HomeTheaterFacade {
    private DVDPlayer dvd;
    private Projector projector;
    private Amplifier amp;
    
    public void watchMovie() {
        dvd.on();
        projector.on();
        amp.on();
        amp.setVolume(5);
        dvd.play();
    }
}

Proxy - контролируемый доступ к другому объекту:

public interface Image {
    void display();
}

public class RealImage implements Image {
    private String filename;
    public RealImage(String filename) {
        this.filename = filename;
        loadImageFromDisk();
    }
    public void display() { System.out.println("Displaying " + filename); }
}

public class ProxyImage implements Image {
    private String filename;
    private RealImage realImage;
    
    public ProxyImage(String filename) { this.filename = filename; }
    
    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename);
        }
        realImage.display();
    }
}

Bridge - отделение абстракции от реализации:

public interface Shape {
    void draw();
}

public abstract class Shape {
    protected Color color;
    public abstract void draw();
}

public class Circle extends Shape {
    public void draw() {
        color.apply();
        System.out.println("Drawing circle");
    }
}

Composite - трёхуровневое древовидное объединение объектов:

public abstract class Component {
    public abstract void operation();
}

public class Leaf extends Component {
    public void operation() { System.out.println("Leaf operation"); }
}

public class Composite extends Component {
    private List<Component> children = new ArrayList<>();
    
    public void add(Component component) { children.add(component); }
    
    public void operation() {
        children.forEach(c -> c.operation());
    }
}

3. BEHAVIORAL Паттерны (Поведенческие)

Отвечают за определение взаимодействия между объектами.

Observer - уведомление множества объектов об изменениях:

public interface Observer {
    void update(String message);
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();
    
    public void attach(Observer observer) { observers.add(observer); }
    public void notifyAll(String message) {
        observers.forEach(o -> o.update(message));
    }
}

public class ConcreteObserver implements Observer {
    public void update(String message) {
        System.out.println("Received: " + message);
    }
}

Strategy - инкапсуляция семейства алгоритмов:

public interface PaymentStrategy {
    void pay(double amount);
}

public class CreditCardPayment implements PaymentStrategy {
    public void pay(double amount) { System.out.println("Paid " + amount); }
}

public class PaymentContext {
    private PaymentStrategy strategy;
    
    public void setStrategy(PaymentStrategy strategy) { this.strategy = strategy; }
    public void executePayment(double amount) { strategy.pay(amount); }
}

Command - инкапсуляция запросов как объектов:

public interface Command {
    void execute();
}

public class OpenFileCommand implements Command {
    private FileSystem fileSystem;
    private String filename;
    
    public void execute() { fileSystem.openFile(filename); }
}

public class Invoker {
    private Command command;
    public void setCommand(Command command) { this.command = command; }
    public void executeCommand() { command.execute(); }
}

State - изменение поведения в зависимости от состояния:

public interface State {
    void handle(Context context);
}

public class ConcreteStateA implements State {
    public void handle(Context context) {
        System.out.println("Handle in state A");
        context.setState(new ConcreteStateB());
    }
}

public class Context {
    private State state;
    public void setState(State state) { this.state = state; }
    public void request() { state.handle(this); }
}

Template Method - определение скелета алгоритма:

public abstract class DataProcessor {
    public final void process() {
        readData();
        parseData();
        analyzeData();
        saveResults();
    }
    
    protected abstract void readData();
    protected abstract void parseData();
    protected abstract void analyzeData();
    protected abstract void saveResults();
}

Chain of Responsibility - цепочка обработчиков:

public abstract class Handler {
    protected Handler nextHandler;
    public abstract void handle(Request request);
}

public class ConcreteHandler extends Handler {
    public void handle(Request request) {
        if (canHandle(request)) {
            process(request);
        } else if (nextHandler != null) {
            nextHandler.handle(request);
        }
    }
}

Iterator - последовательный доступ к элементам коллекции:

public class Collection {
    private Object[] items;
    public Iterator iterator() { return new Iterator(items); }
}

Visitor - добавление операций к объектам без их изменения:

public interface Element {
    void accept(Visitor visitor);
}

public interface Visitor {
    void visit(ConcreteElementA element);
    void visit(ConcreteElementB element);
}

Таблица всех 23 паттернов

Порождающие (5): Singleton, Factory Method, Abstract Factory, Builder, Prototype

Структурные (7): Adapter, Bridge, Composite, Decorator, Facade, Proxy, Flyweight

Поведенческие (11): Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor

Best Practices

✓ Используйте паттерны для решения конкретных проблем ✓ Не переусложняйте код - YAGNI (You Aren't Gonna Need It) ✓ Комбинируйте паттерны когда это имеет смысл ✓ Spring Framework реализует множество паттернов (Singleton, Factory, Proxy) ✓ Изучайте паттерны которые используются в существующем коде ✓ Помните про SOLID принципы при выборе паттерна

GoF паттерны - это фундамент современного OOP проектирования.