Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create prototype1 #3075

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions prototype1
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.HashMap;
import java.util.Map;

// Prototype interface
interface Prototype {
Prototype clone();
}

// Concrete class implementing the Prototype interface
class Shape implements Prototype {
private String type;

public Shape(String type) {
this.type = type;
}

@Override
public Prototype clone() {
return new Shape(this.type);
}

public String getType() {
return type;
}
}

// Prototype registry
class ShapeRegistry {
private Map<String, Shape> shapeMap = new HashMap<>();

public ShapeRegistry() {
loadShapes();
}

private void loadShapes() {
Shape circle = new Shape("Circle");
Shape square = new Shape("Square");

shapeMap.put("Circle", circle);
shapeMap.put("Square", square);
}

public Shape getShape(String shapeType) {
Shape cachedShape = shapeMap.get(shapeType);
return (Shape) cachedShape.clone();
}
}

// Client
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeRegistry shapeRegistry = new ShapeRegistry();

Shape clonedShape1 = shapeRegistry.getShape("Circle");
System.out.println("Shape : " + clonedShape1.getType());

Shape clonedShape2 = shapeRegistry.getShape("Square");
System.out.println("Shape : " + clonedShape2.getType());
}
}