Skip to content

Commit 94a8781

Browse files
authored
Create prototype1
1 parent 7c8802e commit 94a8781

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

prototype1

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
// Prototype interface
5+
interface Prototype {
6+
Prototype clone();
7+
}
8+
9+
// Concrete class implementing the Prototype interface
10+
class Shape implements Prototype {
11+
private String type;
12+
13+
public Shape(String type) {
14+
this.type = type;
15+
}
16+
17+
@Override
18+
public Prototype clone() {
19+
return new Shape(this.type);
20+
}
21+
22+
public String getType() {
23+
return type;
24+
}
25+
}
26+
27+
// Prototype registry
28+
class ShapeRegistry {
29+
private Map<String, Shape> shapeMap = new HashMap<>();
30+
31+
public ShapeRegistry() {
32+
loadShapes();
33+
}
34+
35+
private void loadShapes() {
36+
Shape circle = new Shape("Circle");
37+
Shape square = new Shape("Square");
38+
39+
shapeMap.put("Circle", circle);
40+
shapeMap.put("Square", square);
41+
}
42+
43+
public Shape getShape(String shapeType) {
44+
Shape cachedShape = shapeMap.get(shapeType);
45+
return (Shape) cachedShape.clone();
46+
}
47+
}
48+
49+
// Client
50+
public class PrototypePatternDemo {
51+
public static void main(String[] args) {
52+
ShapeRegistry shapeRegistry = new ShapeRegistry();
53+
54+
Shape clonedShape1 = shapeRegistry.getShape("Circle");
55+
System.out.println("Shape : " + clonedShape1.getType());
56+
57+
Shape clonedShape2 = shapeRegistry.getShape("Square");
58+
System.out.println("Shape : " + clonedShape2.getType());
59+
}
60+
}

0 commit comments

Comments
 (0)