added lab11 ex1

This commit is contained in:
Louis Heredero 2024-11-04 12:54:46 +01:00
parent f37a8cd665
commit 475afc0db5
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
7 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package lab11_flyweight.ex1;
public class Brush implements DrawingTool {
private final Props props;
public Brush(Props props) {
this.props = props;
}
@Override
public void draw(String text) {
System.out.println("Drawing '" + text + "' in " + props.size + ", color:" + props.color);
}
public record Props(Size size, Color color) {}
}

View File

@ -0,0 +1,17 @@
package lab11_flyweight.ex1;
import java.util.HashMap;
import java.util.Map;
public class BrushFactory {
private final Map<Brush.Props, Brush> brushes = new HashMap<>();
public Brush getBrush(Brush.Props props) {
Brush brush = brushes.get(props);
if (brush == null) {
brush = new Brush(props);
brushes.put(props, brush);
}
return brush;
}
}

View File

@ -0,0 +1,6 @@
package lab11_flyweight.ex1;
public enum Color {
BLUE,
RED
}

View File

@ -0,0 +1,5 @@
package lab11_flyweight.ex1;
public interface DrawingTool {
void draw(String text);
}

View File

@ -0,0 +1,31 @@
package lab11_flyweight.ex1;
public class Main {
public static void main(String[] args) {
BrushFactory factory = new BrushFactory();
Brush.Props props1 = new Brush.Props(Size.THICK, Color.RED);
Brush.Props props2 = new Brush.Props(Size.THIN, Color.BLUE);
DrawingTool brush1 = factory.getBrush(props1);
DrawingTool brush2 = factory.getBrush(props1);
brush1.draw("I am drawing with my first thick red brush");
brush2.draw("I am drawing with my second thick red brush");
System.out.println("first thick red brush hashcode: " + brush1.hashCode());
System.out.println("second thick red brush hashcode: " + brush2.hashCode());
System.out.println();
DrawingTool pencil = new Pencil();
pencil.draw("Bonjour");
System.out.println();
DrawingTool brush3 = factory.getBrush(props2);
DrawingTool brush4 = factory.getBrush(props2);
brush3.draw("I am drawing with my first thin blue brush");
brush4.draw("I am drawing with my second thin blue brush");
System.out.println("first thin blue brush hashcode: " + brush3.hashCode());
System.out.println("second thin blue brush hashcode: " + brush4.hashCode());
}
}

View File

@ -0,0 +1,8 @@
package lab11_flyweight.ex1;
public class Pencil implements DrawingTool {
@Override
public void draw(String text) {
System.out.println("Pencil writes some content: " + text);
}
}

View File

@ -0,0 +1,6 @@
package lab11_flyweight.ex1;
public enum Size {
THIN,
THICK
}