Illustration of coding design patterns in Java with examples

Common coding design patterns with java examples

Coding design patterns are like formulas for solving common problems in software development. They’ve tried strategies that you can modify to your specific project needs, making your coding process flatter and your code healthier and maintainable. Let’s join in to some popular design patterns in Java, enhancing them with real-world examples to see how they can be applied.

Singleton Pattern

Visualize you’re running a cafe, and you have only one coffee machine. No matter how many barmen you have, they all share this single machine to brew coffee. This is what the Singleton Pattern does in the coding world. It ensures that a class has just one instance and provides a way to access it globally. This pattern is perfect when you need to manage resources centrally, like a database connection.

Here’s how it looks in Java:

public class CoffeeMachine {
    private static CoffeeMachine instance = null;

    private CoffeeMachine() {}

    public static CoffeeMachine getInstance() {
        if (instance == null) {
            instance = new CoffeeMachine();
        }
        return instance;
    }
}

2. Observer Pattern

Think of a weather station that sends out updates whenever the weather changes. Newspapers, TV channels, and websites subscribe to these updates to inform people. The Observer Pattern works similarly in programming, allowing objects to subscribe to event notifications from other objects. This pattern is fantastic for creating event-driven applications.

Here’s a quick example in Java:

public class WeatherStation {
    private List<Observer> observers = new ArrayList<>();
    private int temperature;

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature);
        }
    }

    public void setTemperature(int temperature) {
        this.temperature = temperature;
        notifyObservers();
    }
}

3. Factory Pattern

Envision you’re an architect choosing between building a house, an apartment, or a villa. You have criteria but decide at the last moment. The Factory Pattern in coding lets you create objects without specifying the exact class of object that will be created. This pattern polishes when you have a superclass with multiple subclasses but want to leave the choice of which subclass to instantiate up to the clients.

Here’s how you can implement it in Java:

interface Building {
    void design();
}

class House implements Building {
    public void design() {
        System.out.println("Designing a cozy house.");
    }
}

class Apartment implements Building {
    public void design() {
        System.out.println("Designing a high-rise apartment.");
    }
}

class BuildingFactory {
    public Building getBuilding(String buildingType) {
        if ("HOUSE".equalsIgnoreCase(buildingType)) {
            return new House();
        } else if ("APARTMENT".equalsIgnoreCase(buildingType)) {
            return new Apartment();
        }
        return null;
    }
}

And to use the factory:

public class ArchitectureSimulator {
    public static void main(String[] args) {
        BuildingFactory factory = new BuildingFactory();
        
        Building myHouse = factory.getBuilding("HOUSE");
        myHouse.design();
        
        Building myApartment = factory.getBuilding("APARTMENT");
        myApartment.design();
    }
}

By understanding and leveraging these patterns, developers can write clearer more efficient code. These patterns offer a structured approach to problem-solving in software development, allowing for more manageable and scalable codebases.

Leave a Reply

Your email address will not be published. Required fields are marked *