JavaRush /Java Blog /Random EN /Design Patterns in Java [Part 2]
Ivan Zaitsev
Level 33
Киев

Design Patterns in Java [Part 2]

Published in the Random EN group
Hi all. In my old topic I briefly described each pattern, in this topic I will try to show in detail how to use the patterns.
Design Patterns in Java [Part 2] - 1

Generative

Singleton

Description :
  • Limits the creation of one instance of a class and provides access to its only object. The class constructor is private. The method getInstance()creates only one instance of the class.
Implementation:
class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
		}
        return instance;
    }
    public void setUp() {
        System.out.println("setUp");
    }
}

public class SingletonTest {//тест
    public static void main(String[] args){
        Singleton singelton = Singleton.getInstance();
        singelton.setUp();
    }
}

Factory

Description :
  • Used when we have a super class with multiple subclasses and based on the input we need to return one from the subclass. The class does not know what type of object it should create. Objects are created depending on the incoming data.
Implementation:
class Factory {
    public OS getCurrentOS(String inputos) {
        OS os = null;
        if (inputos.equals("windows")) {
            os = new windowsOS();
        } else if (inputos.equals("linux")) {
            os = new linuxOS();
        } else if (inputos.equals("mac")) {
            os = new macOS();
        }
        return os;
    }
}
interface OS {
    void getOS();
}
class windowsOS implements OS {
    public void getOS () {
        System.out.println("применить для виндовс");
    }
}
class linuxOS implements OS {
    public void getOS () {
        System.out.println("применить для линукс");
    }
}
class macOS implements OS {
    public void getOS () {
        System.out.println("применить для мак");
    }
}

public class FactoryTest {//тест
    public static void main(String[] args){
        String win = "linux";
        Factory factory = new Factory();
        OS os = factory.getCurrentOS(win);
        os.getOS();
    }
}

Abstract Factory

Description :
  • Allows you to select a specific factory implementation from a family of possible factories. Creates a family of related objects. Easy to expand.
Implementation:
interface Lada {
    long getLadaPrice();
}
interface Ferrari {
    long getFerrariPrice();
}
interface Porshe {
    long getPorshePrice();
}
interface InteAbsFactory {
    Lada getLada();
    Ferrari getFerrari();
    Porshe getPorshe();
}
class UaLadaImpl implements Lada {// первая
    public long getLadaPrice() {
        return 1000;
    }
}
class UaFerrariImpl implements Ferrari {
    public long getFerrariPrice() {
        return 3000;
    }
}
class UaPorsheImpl implements Porshe {
    public long getPorshePrice() {
        return 2000;
    }
}
class UaCarPriceAbsFactory implements InteAbsFactory {
    public Lada getLada() {
        return new UaLadaImpl();
    }
    public Ferrari getFerrari() {
        return new UaFerrariImpl();
    }
    public Porshe getPorshe() {
        return new UaPorsheImpl();
    }
}// первая
class RuLadaImpl implements Lada {// вторая
    public long getLadaPrice() {
        return 10000;
    }
}
class RuFerrariImpl implements Ferrari {
    public long getFerrariPrice() {
        return 30000;
    }
}
class RuPorsheImpl implements Porshe {
    public long getPorshePrice() {
        return 20000;
    }
}
class RuCarPriceAbsFactory implements InteAbsFactory {
    public Lada getLada() {
        return new RuLadaImpl();
    }
    public Ferrari getFerrari() {
        return new RuFerrariImpl();
    }
    public Porshe getPorshe() {
        return new RuPorsheImpl();
    }
}// вторая

public class AbstractFactoryTest {//тест
    public static void main(String[] args) {
        String country = "UA";
        InteAbsFactory ifactory = null;
        if(country.equals("UA")) {
            ifactory = new UaCarPriceAbsFactory();
        } else if(country.equals("RU")) {
            ifactory = new RuCarPriceAbsFactory();
        }

        Lada lada = ifactory.getLada();
        System.out.println(lada.getLadaPrice());
    }
}

Builder

Description :
  • Used to create a complex object using simple objects. Gradually it creates a larger object from a small and simple object. Allows you to change the internal representation of the final product.
Implementation:
class Car {
    public void buildBase() {
        print("Doing корпус");
    }
    public void buildWheels() {
        print("Ставим колесо");
    }
    public void buildEngine(Engine engine) {
        print("Ставим движок: " + engine.getEngineType());
    }
    private void print(String msg){
        System.out.println(msg);
    }
}
interface Engine {
    String getEngineType();
}
class OneEngine implements Engine {
    public String getEngineType() {
        return "Первый двигатель";
    }
}
class TwoEngine implements Engine {
    public String getEngineType() {
        return "Второй двигатель";
    }
}
abstract class Builder {
    protected Car car;
    public abstract Car buildCar();
}
class OneBuilderImpl extends Builder {
    public OneBuilderImpl(){
        car = new Car();
    }
    public Car buildCar() {
        car.buildBase();
        car.buildWheels();
        Engine engine = new OneEngine();
        car.buildEngine(engine);
        return car;
    }
}
class TwoBuilderImpl extends Builder {
    public TwoBuilderImpl(){
        car = new Car();
    }
    public Car buildCar() {
        car.buildBase();
        car.buildWheels();
        Engine engine = new OneEngine();
        car.buildEngine(engine);
        car.buildWheels();
        engine = new TwoEngine();
        car.buildEngine(engine);
        return car;
    }
}
class Build {
    private Builder builder;
    public Build(int i){
        if(i == 1) {
            builder = new OneBuilderImpl();
        } else if(i == 2) {
            builder = new TwoBuilderImpl();
        }
    }
    public Car buildCar(){
        return builder.buildCar();
    }
}

public class BuilderTest {//тест
    public static void main(String[] args) {
        Build build = new Build(1);
        build.buildCar();
    }
}

Prototype

Description :
  • Helps to create a duplicate object with better performance, instead of creating a new one, a returned clone of the existing object is created. Clones an existing object.
Implementation:
interface Copyable {
    Copyable copy();
}
class ComplicatedObject implements Copyable {
    private Type type;
    public enum Type {
        ONE, TWO
    }
    public ComplicatedObject copy() {
        ComplicatedObject complicatedobject = new ComplicatedObject();
        return complicatedobject;
    }
    public void setType(Type type) {
        this.type = type;
    }
}

public class PrototypeTest {//тест
    public static void main(String[] args) {
        ComplicatedObject prototype = new ComplicatedObject();
        ComplicatedObject clone = prototype.copy();
        clone.setType(ComplicatedObject.Type.ONE);
    }
}

Structural

Adapter

Description :
  • Using a pattern, we can combine two incompatible objects. Converter between two incompatible objects.
Implementation:
class PBank {
	private int balance;
	public PBank() { balance = 100; }
	public void getBalance() {
		System.out.println("PBank balance = " + balance);
	}
}
class ABank {
	private int balance;
	public ABank() { balance = 200; }
	public void getBalance() {
		System.out.println("ABank balance = " + balance);
	}
}
class PBankAdapter extends PBank {
	private ABank abank;
	public PBankAdapter(ABank abank) {
		this.abank = abank;
	}
	public void getBalance() {
		abank.getBalance();
	}
}

public class AdapterTest {//тест
	public static void main(String[] args) {
		PBank pbank = new PBank();
		pbank.getBalance();
		PBankAdapter abank = new PBankAdapter(new ABank());
		abank.getBalance();
	}
}

Composite

Description :
  • Groups multiple objects into a tree structure using a single class. Allows you to work with several classes through one object.
Implementation:
import java.util.ArrayList;
import java.util.List;
interface Car {
    void draw(String color);
}
class SportCar implements Car {
    public void draw(String color) {
        System.out.println("SportCar color: " + color);
    }
}
class UnknownCar implements Car {
    public void draw(String color) {
        System.out.println("UnknownCar color: " + color);
    }
}
class Drawing implements Car {
    private List<Car> cars = new ArrayList<Car>();
    public void draw(String color) {
        for(Car car : cars) {
            car.draw(color);
        }
    }
    public void add(Car s){
        this.cars.add(s);
    }
    public void clear(){
		System.out.println();
        this.cars.clear();
    }
}

public class CompositeTest {//тест
    public static void main(String[] args) {
        Car sportCar = new SportCar();
        Car unknownCar = new UnknownCar();
        Drawing drawing = new Drawing();
        drawing.add(sportCar);
        drawing.add(unknownCar);
        drawing.draw("green");
        drawing.clear();
        drawing.add(sportCar);
        drawing.add(unknownCar);
        drawing.draw("white");
    }
}

Proxy

Description :
  • Represents objects that can control other objects by intercepting their calls. It is possible to intercept the call to the original object.
Implementation:
interface Image {
    void display();
}
class RealImage implements Image {
    private String file;
    public RealImage(String file){
        this.file = file;
        load(file);
    }
    private void load(String file){
        System.out.println("Загрузка " + file);
    }
    public void display() {
        System.out.println("Просмотр " + file);
    }
}
class ProxyImage implements Image {
    private String file;
    private RealImage image;
    public ProxyImage(String file){
        this.file = file;
    }
    public void display() {
        if(image == null){
            image = new RealImage(file);
        }
        image.display();
    }
}

public class ProxyTest {//тест
    public static void main(String[] args) {
        Image image = new ProxyImage("test.jpg");
        image.display();
        image.display();
    }
}

Flyweight

Description :
  • Instead of creating a large number of similar objects, objects are reused. Saves memory.
Implementation:
class Flyweight {
    private int row;
    public Flyweight(int row) {
        this.row = row;
        System.out.println("ctor: " + this.row);
    }
    void report(int col) {
        System.out.print(" " + row + col);
    }
}

class Factory {
    private Flyweight[] pool;
    public Factory(int maxRows) {
        pool = new Flyweight[maxRows];
    }
    public Flyweight getFlyweight(int row) {
        if (pool[row] == null) {
            pool[row] = new Flyweight(row);
        }
        return pool[row];
    }
}

public class FlyweightTest {//тест
    public static void main(String[] args) {
        int rows = 5;
        Factory theFactory = new Factory(rows);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < rows; j++) {
                theFactory.getFlyweight(i).report(j);
            }
            System.out.println();
        }
    }
}

Facade

Description :
  • Hides a complex class system by casting all calls to a single object. Places a call to multiple complex objects into a single object.
Implementation:
interface Car {
    void start();
    void stop();
}
class Key implements Car {
    public void start() {
        System.out.println("Вставить ключи");
    }
    public void stop() {
        System.out.println("Вытянуть ключи");
    }
}
class Engine implements Car {
    public void start() {
        System.out.println("Запустить двигатель");
    }
    public void stop() {
        System.out.println("Остановить двигатель");
    }
}
class Facade {
    private Key key;
    private Engine engine;
    public Facade() {
        key = new Key();
        engine = new Engine();
    }
    public void