코드를 클래스에 의존시키지 않고 기존 객체를 복사할 수 있도록 하는 생성 디자인 패턴
abstract class Shape {
int x;
int y;
String color;
public Shape() {
}
// 프로토타입 생성자
public Shape(Shape source) {
if (source != null) {
this.x = source.x;
this.y = source.y;
this.color = source.color;
}
}
// 복제 메서드
public abstract Shape clone();
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle() {
}
public Rectangle(Rectangle source) {
super(source);
if (source != null) {
this.width = source.width;
this.height = source.height;
}
}
@Override
public Shape clone() {
return new Rectangle(this);
}
}
class Circle extends Shape {
int radius;
public Circle() {
}
public Circle(Circle source) {
super(source);
if (source != null) {
this.radius = source.radius;
}
}
@Override
public Shape clone() {
return new Circle(this);
}
}
class ShapeRegistry {
private Map<String, Shape> shapes = new HashMap<>();
public void addShape(String key, Shape shape) {
shapes.put(key, shape);
}
public Shape getShape(String key) {
Shape shape = shapes.get(key);
if (shape != null) {
return shape.clone();
}
throw new IllegalArgumentException("Shape not found: " + key);
}
}
class Application {
List<Shape> shapes = new ArrayList<>();
ShapeRegistry registry;
public Application() {
registry = new ShapeRegistry();
Circle defaultCircle = new Circle();
defaultCircle.x = 10;
defaultCircle.y = 10;
defaultCircle.radius = 20;
defaultCircle.color = "Red";
registry.addShape("circle", defaultCircle);
Rectangle defaultRectangle = new Rectangle();
defaultRectangle.x = 15;
defaultRectangle.y = 25;
defaultRectangle.width = 10;
defaultRectangle.height = 20;
defaultRectangle.color = "Blue";
registry.addShape("rectangle", defaultRectangle);
shapes.add(registry.getShape("circle"));
shapes.add(registry.getShape("rectangle"));
}
public void businessLogic() {
List<Shape> shapesCopy = new ArrayList<>();
for (Shape s : shapes) {
shapesCopy.add(s.clone());
}
System.out.println("Original Shapes: " + shapes.size());
System.out.println("Copied Shapes: " + shapesCopy.size());
}
public static void main(String[] args) {
Application app = new Application();
app.businessLogic();
}
}