Java Design Patterns: Practical Code Examples

Singleton Pattern

class Singleton {
    private static Singleton instance;
    private Singleton() {}

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

public class Main {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

Factory Pattern

interface Animal { void speak();}

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

class Cat implements Animal { public void speak() {   System.out.println("Meow");  }}

abstract class AnimalFactory {
    abstract Animal createAnimal();
}

class DogFactory extends AnimalFactory {
    Animal createAnimal() {
        return new Dog();
    }
}

class CatFactory extends AnimalFactory {
    Animal createAnimal() {
        return new Cat();
    }
}

public class Main {
    public static void main(String[] args) {
        AnimalFactory factory = new DogFactory();
        Animal animal = factory.createAnimal();
        animal.speak();
    }
}

Abstract Factory Pattern

interface Button {  void paint();}

interface Checkbox {void check();}

class WindowsButton implements Button {
    public void paint() {
        System.out.println("Windows Button");
    }
}

class WindowsCheckbox implements Checkbox {
    public void check() {
        System.out.println("Windows Checkbox");
    }
}

class MacButton implements Button {
    public void paint() {
        System.out.println("Mac Button");
    }
}

class MacCheckbox implements Checkbox {
    public void check() {
        System.out.println("Mac Checkbox");
    }
}

interface GUIFactory {
    Button createButton(); Checkbox createCheckbox();
}

class WindowsFactory implements GUIFactory {
    public Button createButton() {
        return new WindowsButton();
    }

    public Checkbox createCheckbox() {
        return new WindowsCheckbox();
    }
}

class MacFactory implements GUIFactory {
    public Button createButton() {
        return new MacButton();
    }

    public Checkbox createCheckbox() {
        return new MacCheckbox();
    }
}

public class Main {  public static void main(String[] args) {
    GUIFactory factory = new WindowsFactory();
    Button button = factory.createButton();
    Checkbox checkbox = factory.createCheckbox();
    button.paint();    checkbox.check();
} }

Builder Pattern

class Car {  private String color;
    private String engine;

    public void setColor(String color) {
        this.color = color;
    }

    public void setEngine(String engine) {
        this.engine = engine;
    }

    public void show() {
        System.out.println(color + " " + engine);
    }
}

class CarBuilder {
    private Car car = new Car();

    public CarBuilder setColor(String color) {
        car.setColor(color);    return this;
    }

    public CarBuilder setEngine(String engine) {
        car.setEngine(engine);    return this;
    }

    public Car build() {   return car;    }
}

public class Main {  public static void main(String[] args) {
    Car car = new CarBuilder()
            .setColor("Red")
            .setEngine("V8")    .build();    car.show();
}}

Prototype Pattern

class Car implements Cloneable { private String color;

    public Car(String color) {    this.color = color;    }

    public Car clone() {        return new Car(color);}

    public void show() {        System.out.println(color);} }

public class Main {   public static void main(String[] args) {
    Car car1 = new Car("Red");
    Car car2 = car1.clone();     car2.show();
} }

Adapter Pattern

interface MediaPlayer { void play();}

class OldPlayer {  public void startMusic() {
        System.out.println("Playing music");
    } }

class PlayerAdapter implements MediaPlayer {
    private OldPlayer oldPlayer;

    public PlayerAdapter(OldPlayer oldPlayer) {
        this.oldPlayer = oldPlayer;
    }

    public void play() {    oldPlayer.startMusic();    }
}

public class Main {  public static void main(String[] args) {
    MediaPlayer player =
            new PlayerAdapter(new OldPlayer());
    player.play();
} }

Bridge Pattern

interface Color {    void applyColor();}

class Red implements Color {  public void applyColor() {
        System.out.println("Red");
    }}

class Blue implements Color {    public void applyColor() {
        System.out.println("Blue");
    } }

abstract class Shape {    protected Color color;

    public Shape(Color color) {        this.color = color;
    }

    abstract void draw(); }

class Circle extends Shape {    public Circle(Color color) {
        super(color);
    }

    public void draw() {      System.out.print("Circle ");
        color.applyColor();
    } }

public class Main {  public static void main(String[] args) {     Shape shape = new Circle(new Red());
    shape.draw();
}}

Composite Pattern

interface Component {    void show();}

class FileItem implements Component {
    public void show() {    System.out.println("File");    }
}

class Folder implements Component {
    private List<Component> children =      new ArrayList<>();

    public void add(Component c) {      children.add(c);    }

    public void show() {    System.out.println("Folder");
        for (Component c : children) {     c.show();        }
    }
}

public class Main {    public static void main(String[] args) {
    Folder folder = new Folder();
    folder.add(new FileItem());
    folder.add(new FileItem());
    folder.show();
} }

Decorator Pattern

interface Coffee {    String getDescription();}

class BasicCoffee implements Coffee {
    public String getDescription() {
        return "Coffee";
    }
}

abstract class CoffeeDecorator
        implements Coffee {  protected Coffee coffee;

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

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

    public String getDescription() {
        return coffee.getDescription()   + " + Milk";
    }
}

public class Main {    public static void main(String[] args) {
    Coffee coffee =  new MilkDecorator(   new BasicCoffee());
    System.out.println(           coffee.getDescription());
}}

Facade Pattern

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

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

class HardDrive {    void read() {
        System.out.println("Hard Drive Read");
    }}

class ComputerFacade { private CPU cpu = new CPU();
    private Memory memory = new Memory();
    private HardDrive hardDrive =     new HardDrive();

    public void startComputer() {    cpu.start();
        memory.load();       hardDrive.read();
        System.out.println("Computer Started");
    }}

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

Command Pattern

interface Command {   void execute();}

class Light {
    public void on() { System.out.println("Light ON");    }
}

class LightOnCommand
        implements Command {  private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    public void execute() {   light.on();    }
}

class Remote {private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {   command.execute();   }}

public class Main {  public static void main(String[] args) {
    Light light = new Light();
    Command command =
            new LightOnCommand(light);
    Remote remote = new Remote();
    remote.setCommand(command);
    remote.pressButton();
}}

Observer Pattern

interface Observer {    void update();}

class User implements Observer {
    private String name;

    public User(String name) {
        this.name = name;   }

    public void update() {
        System.out.println(
                name + " received notification");    }
}

class Channel {
    private List<Observer> observers =     new ArrayList<>();

    public void subscribe(
            Observer observer) {
        observers.add(observer);    }    public void notifyUsers() {
    for (Observer observer : observers) { observer.update();   }}}

public class Main {  public static void main(String[] args) {
    Channel channel =   new Channel();
    channel.subscribe( new User("Ali"));
    channel.subscribe( new User("Sara"));
    channel.notifyUsers();  }}

Strategy Pattern

interface PaymentStrategy { void pay();}

class CreditCard
        implements PaymentStrategy { public void pay() {
        System.out.println(   "Paid using Credit Card");    }}

class PayPal
        implements PaymentStrategy {public void pay() {
        System.out.println( "Paid using PayPal");    }}

class ShoppingCart {
    private PaymentStrategy strategy; public void setStrategy(
            PaymentStrategy strategy) { this.strategy = strategy;    }

    public void checkout() {   strategy.pay();   }}

public class Main { public static void main(String[] args) {
    ShoppingCart cart =  new ShoppingCart();
    cart.setStrategy(   new CreditCard());   cart.checkout();
    cart.setStrategy(  new PayPal());cart.checkout();
}}