Created
February 22, 2024 09:51
-
-
Save alexjosesilva/9e9e9ff4b9e99e63683fb16c7a3c29fa to your computer and use it in GitHub Desktop.
Factory Method (Método de Fábrica)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Interface para representar diferentes formas geométricas | |
interface Shape { | |
void draw(); | |
} | |
// Implementação da interface para um círculo | |
class Circle implements Shape { | |
@Override | |
public void draw() { | |
System.out.println("Desenhando um círculo"); | |
} | |
} | |
// Implementação da interface para um quadrado | |
class Square implements Shape { | |
@Override | |
public void draw() { | |
System.out.println("Desenhando um quadrado"); | |
} | |
} | |
// Fábrica para criar diferentes formas geométricas | |
class ShapeFactory { | |
// Método de fábrica para obter uma forma com base no tipo fornecido | |
public Shape getShape(String shapeType) { | |
if (shapeType == null) { | |
return null; | |
} | |
if (shapeType.equalsIgnoreCase("CIRCLE")) { | |
return new Circle(); | |
} else if (shapeType.equalsIgnoreCase("SQUARE")) { | |
return new Square(); | |
} | |
return null; | |
} | |
} | |
// Classe principal para testar o Factory Method | |
public class Main { | |
public static void main(String[] args) { | |
// Criando uma instância da fábrica | |
ShapeFactory shapeFactory = new ShapeFactory(); | |
// Obtendo diferentes formas usando o método de fábrica | |
Shape circle = shapeFactory.getShape("CIRCLE"); | |
if (circle != null) { | |
circle.draw(); // Deve imprimir "Desenhando um círculo" | |
} | |
Shape square = shapeFactory.getShape("SQUARE"); | |
if (square != null) { | |
square.draw(); // Deve imprimir "Desenhando um quadrado" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment