Structural design patterns deal with the composition of classes and objects to create larger, more complex structures while keeping the system flexible and easy to maintain. They are concerned with object relationships and the assembly of objects to form more significant structures. These patterns help to solve common design problems by promoting object reusability and flexibility.

Adapter Pattern

The Adapter Pattern allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, making them work seamlessly.

Example

interface NewInterface {
    void doSomethingNew();
}

class LegacyLibrary {
    void doSomethingOld() {
        // Legacy implementation
        System.out.println("Legacy implementation");
    }
}

class LegacyAdapter implements NewInterface {
    private LegacyLibrary legacyLibrary;

    public LegacyAdapter(LegacyLibrary legacyLibrary) {
        this.legacyLibrary = legacyLibrary;
    }

    @Override
    public void doSomethingNew() {
        legacyLibrary.doSomethingOld();
    }
}

public class Main {
    public static void main(String[] args) {
        NewInterface newObject = new LegacyAdapter(new LegacyLibrary());
        newObject.doSomethingNew();
    }
}

Bridge Pattern

The Bridge Pattern separates an object's abstraction from its implementation, allowing them to vary independently.

Example

interface DrawingAPI {
    void drawCircle(double x, double y, double radius);
}

class DrawingAPI1 implements DrawingAPI {
    public void drawCircle(double x, double y, double radius) {
        System.out.println("Implementation 1");
    }
}

class DrawingAPI2 implements DrawingAPI {
    public void drawCircle(double x, double y, double radius) {
        System.out.println("Implementation 2");
    }
}

abstract class Shape {
    protected DrawingAPI drawingAPI;

    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }

    public abstract void draw();
}

class Circle extends Shape {
    private double x, y, radius;

    public Circle(double x, double y, double radius, DrawingAPI drawingAPI) {
        super(drawingAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public void draw() {
        drawingAPI.drawCircle(x, y, radius);
    }
}

public class Main {
    public static void main(String[] args) {
        DrawingAPI api1 = new DrawingAPI1();
        Shape circle1 = new Circle(1, 2, 3, api1);
        circle1.draw();
    }
}

Composite Pattern

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It treats individual objects and compositions of objects uniformly.

Example

import java.util.ArrayList;
import java.util.List;

interface Graphic {
    void draw();
}

class Circle implements Graphic {
    public void draw() {
        System.out.println("Drawing circle.");
    }
}

class Square implements Graphic {
    public void draw() {
        System.out.println("Drawing square.");
    }
}

class CompositeGraphic implements Graphic {
    private List<Graphic> graphics = new ArrayList<>();

    public void add(Graphic graphic) {
        graphics.add(graphic);
    }

    public void draw() {
        System.out.println("Drawing all graphics.");
        for (Graphic graphic : graphics) {
            graphic.draw();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        CompositeGraphic composite = new CompositeGraphic();
        composite.add(new Circle());
        composite.add(new Square());
        composite.draw();
    }
}

Decorator Pattern

The Decorator Pattern allows you to add behavior to objects dynamically, without altering their class.

Example

interface Coffee {
    double cost();
    String description();
}

class SimpleCoffee implements Coffee {
    public double cost() {
        return 2.0;
    }

    public String description() {
        return "Simple Coffee";
    }
}

abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }

    public double cost() {
        return decoratedCoffee.cost();
    }

    public String description() {
        return decoratedCoffee.description();
    }
}

class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double cost() {
        return super.cost() + 1.0;
    }

    public String description() {
        return super.description() + ", Milk";
    }
}

public class Main {
    public static void main(String[] args) {
        Coffee coffee = new MilkDecorator(new SimpleCoffee());
        System.out.println("Cost: $" + coffee.cost());
        System.out.println("Description: " + coffee.description());
    }
}

Facade Pattern

The Facade Pattern provides a simplified interface to a complex system of classes, making it easier to use and understand. It acts as a "facade" or entry point to access a group of related interfaces and classes.

Example

class CPU {
    public void start() {
        System.out.println("CPU start");
    }

    public void shutdown() {
        System.out.println("CPU shutdown");
    }
}

class Memory {
    public void load() {
        System.out.println("Memory load");
    }

    public void unload() {
        System.out.println("Memory unload");
    }
}

class HardDrive {
    public void read() {
        System.out.println("Hard drive read");
    }

    public void write() {
        System.out.println("Hard drive write");
    }
}

class ComputerFacade {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public ComputerFacade() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void start() {
        cpu.start();
        memory.load();
        hardDrive.read();
    }

    public void shutdown() {
        cpu.shutdown();
        memory.unload();
        hardDrive.write();
    }
}

public class Main {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
        computer.shutdown();
    }
}

Filter Pattern

The Filter Pattern allows you to create a chain of filter objects to process a request. Each filter performs some filtering or processing on the request and passes it to the next filter in the chain.

Example

import java.util.ArrayList;
import java.util.List;

class Product {
    private String name;
    private String category;
    private double price;

    public Product(String name, String category, double price) {
        this.name = name;
        this.category = category;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public String getCategory() {
        return category;
    }

    public double getPrice() {
        return price;
    }
}

interface Filter {
    List<Product> filter(List<Product> products);
}

class CategoryFilter implements Filter {
    private String category;

    public CategoryFilter(String category) {
        this.category = category;
    }

    @Override
    public List<Product> filter(List<Product> products) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product product : products) {
            if (product.getCategory().equalsIgnoreCase(category)) {
                filteredProducts.add(product);
            }
        }
        return filteredProducts;
    }
}

class PriceRangeFilter implements Filter {
    private double minPrice;
    private double maxPrice;

    public PriceRangeFilter(double minPrice, double maxPrice) {
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
    }

    @Override
    public List<Product> filter(List<Product> products) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product product : products) {
            double price = product.getPrice();
            if (price >= minPrice && price <= maxPrice) {
                filteredProducts.add(product);
            }
        }
        return filteredProducts;
    }
}

class ProductFilter {
    public static List<Product> applyFilter(List<Product> products, Filter filter) {
        return filter.filter(products);
    }
}

public class Main {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Laptop", "Electronics", 1000.0));
        products.add(new Product("Phone", "Electronics", 500.0));
        products.add(new Product("Shirt", "Clothing", 25.0));
        products.add(new Product("Dress", "Clothing", 50.0));
        products.add(new Product("Book", "Books", 15.0));

        System.out.println("Electronics products:");
        List<Product> electronicsProducts = ProductFilter.applyFilter(products, new CategoryFilter("Electronics"));
        printProducts(electronicsProducts);

        System.out.println("\nProducts in the price range $20 - $100:");
        List<Product> priceRangeProducts = ProductFilter.applyFilter(products, new PriceRangeFilter(20.0, 100.0));
        printProducts(priceRangeProducts);
    }

    public static void printProducts(List<Product> products) {
        for (Product product : products) {
            System.out.println("Name: " + product.getName() + ", Category: " + product.getCategory() +
                    ", Price: $" + product.getPrice());
        }
    }
}

Flyweight Pattern

The Flyweight Pattern is used to minimize memory usage or computational expenses by sharing as much as possible with related objects. It is particularly useful when you have a large number of similar objects, and you want to reduce memory usage by sharing common data among them.

Example

import java.util.HashMap;
import java.util.Map;

class Character {
    private char symbol;

    public Character(char symbol) {
        this.symbol = symbol;
    }

    public void display(int fontSize) {
        System.out.println("Character: " + symbol + ", Font Size: " + fontSize);
    }
}

class CharacterFactory {
    private Map<java.lang.Character, Character> characters = new HashMap<>();

    public Character getCharacter(char symbol) {
        if (!characters.containsKey(symbol)) {
            characters.put(symbol, new Character(symbol));
        }
        return characters.get(symbol);
    }
}

public class Main {
    public static void main(String[] args) {
        CharacterFactory characterFactory = new CharacterFactory();
        Character charA = characterFactory.getCharacter('A');
        Character charB = characterFactory.getCharacter('B');
        charA.display(12);
        charB.display(16);
    }
}

Proxy Pattern

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it. It allows you to add an additional level of control over object access, such as lazy loading, access control, or monitoring.

Example

interface Image {
    void display();
}

class RealImage implements Image {
    private String filename;

    public RealImage(String filename) {
        this.filename = filename;
        loadFromDisk();
    }

    private void loadFromDisk() {
        System.out.println("Loading " + filename);
    }

    public void display() {
        System.out.println("Displaying " + filename);
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private String filename;

    public ProxyImage(String filename) {
        this.filename = filename;
    }

    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename);
        }
        realImage.display();
    }
}

public class Main {
    public static void main(String[] args) {
        Image image = new ProxyImage("large_image.jpg");
        image.display();
    }
}