Skip to content

Instantly share code, notes, and snippets.

@walteralleyz
Created January 12, 2022 13:45
Show Gist options
  • Save walteralleyz/52a0bd800ba37506346f6a29d1788bf7 to your computer and use it in GitHub Desktop.
Save walteralleyz/52a0bd800ba37506346f6a29d1788bf7 to your computer and use it in GitHub Desktop.
public interface Shape {
void draw();
}
//------------------------------------------------------
//------------------------------------------------------
// Circle.java
// Classe Circle, implementando a interface Shape
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color) {
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius);
}
}
//------------------------------------------------------
//------------------------------------------------------
// ShapeFactory.java
// Classe Factory para produzir e controlar Shapes
import java.util.HashMap;
public class ShapeFactory {
@SuppressWarnings("unchecked")
private static final HashMap circleMap = new HashMap();
public static Shape getCircle(String color) {
Circle circle = (Circle)circleMap.get(color);
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}
//------------------------------------------------------
//------------------------------------------------------
// FlyweightPatternDemo.java
// Classe cliente que utiliza nosso factory
public class FlyweightPatternDemo {
private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
for(int i=0; i < 20; ++i) {
Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
private static int getRandomX() {
return (int)(Math.random()*100 );
}
private static int getRandomY() {
return (int)(Math.random()*100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment