CodeGym /Blogue Java /Random-PT /Padrões de projeto em Java [Parte 2]
John Squirrels
Nível 41
San Francisco

Padrões de projeto em Java [Parte 2]

Publicado no grupo Random-PT
Olá pessoal. Em meu artigo anterior , descrevi brevemente cada padrão. Neste artigo, tentarei mostrar, em detalhes, como usar os padrões.
Padrões de design em Java [Parte 2] - 1

criacional

solteiro

Descrição: restringe a criação de uma classe a uma única instância e fornece acesso a essa única instância. O construtor da classe é privado. O getInstance()método cria apenas uma instância da classe. Implementação:
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 { // Test
    public static void main(String[] args){
        Singleton singelton = Singleton.getInstance();
        singelton.setUp();
    }
}

Fábrica

Descrição: Usado quando temos uma superclasse com várias subclasses e precisamos retornar uma subclasse com base na entrada. A classe não sabe que tipo de objeto deve criar. Os objetos são criados com base nas entradas. Implementação:
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("uses Windows");
    }
}
class linuxOS implements OS {
    public void getOS () {
        System.out.println("uses Linux");
    }
}
class macOS implements OS {
    public void getOS () {
        System.out.println("uses macOS");
    }
}

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

fábrica abstrata

Descrição: permite selecionar uma implementação de fábrica específica de uma família de fábricas possíveis. Cria uma família de objetos relacionados. Fácil de expandir. Implementação:
interface Lada {
    long getLadaPrice();
}
interface Ferrari {
    long getFerrariPrice();
}
interface Porshe {
    long getPorshePrice();
}
interface InteAbsFactory {
    Lada getLada();
    Ferrari getFerrari();
    Porshe getPorshe();
}
class UaLadaImpl implements Lada { // First
    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();
    }
} // First
class RuLadaImpl implements Lada { // Second
    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();
    }
} // Second

public class AbstractFactoryTest { // Test
    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());
    }
}

Construtor

Descrição: Usado para criar um objeto complexo usando objetos simples. Ele gradualmente cria um objeto grande a partir de um objeto pequeno e simples. Permite alterar a representação interna do produto final. Implementação:
class Car {
    public void buildBase() {
        print("Building the base");
    }
    public void buildWheels() {
        print("Installing wheels");
    }
    public void buildEngine(Engine engine) {
        print("Installing engine: " + engine.getEngineType());
    }
    private void print(String msg){
        System.out.println(msg);
    }
}
interface Engine {
    String getEngineType();
}
class EngineOne implements Engine {
    public String getEngineType() {
        return "First engine";
    }
}
class EngineTwo implements Engine {
    public String getEngineType() {
        return "Second engine";
    }
}
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 EngineOne();
        car.buildEngine(engine);
        return car;
    }
}
class TwoBuilderImpl extends Builder {
    public TwoBuilderImpl(){
        car = new Car();
    }
    public Car buildCar() {
        car.buildBase();
        car.buildWheels();
        Engine engine = new EngineOne();
        car.buildEngine(engine);
        car.buildWheels();
        engine = new EngineTwo();
        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 { // Test
    public static void main(String[] args) {
        Build build = new Build(1);
        build.buildCar();
    }
}

Protótipo

Descrição: Ajuda a melhorar o desempenho ao criar objetos duplicados; em vez de criar um novo objeto, ele cria e retorna um clone de um objeto existente. Clona um objeto existente. Implementação:
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 { // Test
    public static void main(String[] args) {
        ComplicatedObject prototype = new ComplicatedObject();
        ComplicatedObject clone = prototype.copy();
        clone.setType(ComplicatedObject.Type.ONE);
    }
}

Estrutural

Adaptador

Descrição: Podemos usar o padrão adaptador para combinar duas interfaces incompatíveis. Ele atua como um conversor entre dois objetos incompatíveis. Implementação:
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 { // Test
	public static void main(String[] args) {
		PBank pbank = new PBank();
		pbank.getBalance();
		PBankAdapter abank = new PBankAdapter(new ABank());
		abank.getBalance();
	}
}

Composto

Descrição: Agrupa vários objetos em uma estrutura de árvore usando uma classe. Permite trabalhar com várias classes através de um único objeto. Implementação:
import java.util.ArrayList;
import java.util.List;
interface Car {
    void draw(String color);
}
class SportsCar implements Car {
    public void draw(String color) {
        System.out.println("SportsCar 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 { // Test
    public static void main(String[] args) {
        Car sportsCar = new SportsCar();
        Car unknownCar = new UnknownCar();
        Drawing drawing = new Drawing();
        drawing.add(sportsCar);
        drawing.add(unknownCar);
        drawing.draw("green");
        drawing.clear();
        drawing.add(sportsCar);
        drawing.add(unknownCar);
        drawing.draw("white");
    }
}

Proxy

Descrição: Representa objetos que podem controlar outros objetos interceptando suas chamadas de método. Você pode interceptar a chamada de método do objeto original. Implementação:
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("Loading " + file);
    }
    public void display() {
        System.out.println("Displaying " + 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 { // Test
    public static void main(String[] args) {
        Image image = new ProxyImage("test.jpg");
        image.display();
        image.display();
    }
}

Peso Mosca

Descrição: Reutiliza objetos em vez de criar um grande número de objetos semelhantes. Economiza memória. Implementação:
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 { // Test
    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();
        }
    }
}

Fachada

Descrição: Oculta um sistema complexo de classes adicionando todas as chamadas a um objeto. Coloca as chamadas de método de vários objetos complexos em um único objeto. Implementação:
interface Car {
    void start();
    void stop();
}
class Key implements Car {
    public void start() {
        System.out.println(