https://www.inflearn.com/course/%EC%9E%90%EB%B0%94-%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4#
사전적 의미의 프로토타입(Prototype)이란?
원형, 원작을 의미한다. 사본이 있다면 그것에 대한 원본이 있기 마련이다.
프로토타입 패턴이란?
생산 비용이 높은 인스턴스를 복사를 통해 쉽게 생성할 수 있도록 하는 패턴을 말한다.
즉, 미리 만들어진 객체(Object)를 복사하여 객체를 생성하는 패턴이다.
이를 통해 객체의 생성 비용을 효과적으로 줄일 수 있다.
복사는 깊은 복사와 얕은 복사로 이루어져 있는데
자세한 사항은 여기를 참조해 주세요
프로토타입을 사용하는 경우
1. 종류가 너무 많아서 클래스로 정리되지 않는 경우
2. 클래스로부터 인스턴스 생성이 어려운 경우
요구사항
일러스트레이터와 같은 그림 그리기 툴을 개발 중입니다.
어떤 모양(Shape)을 그릴 수 있도록 하고 복사 붙여 넣기 기능을 구현해 주세요.
추가 요구사항
복사 후 붙여 넣기를 하면 두 도형이 겹치는데 안 겹치도록 살짝 옆으로 이동해 주세요
Prototype.Circle.java
public class Circle extends Shape{
private int x,y,r;
public Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public Circle copy() throws CloneNotSupportedException {
Circle circle = (Circle) clone();
// 더 공부하기 ----
circle.x = x+1;
circle.y = y+1;
return circle;
}
}
Prototype.Shape
public class Shape implements Cloneable { // Cloneable은 이미 정의되어있는 인터페이스
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
ProtoType.Main
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Circle circle1 = new Circle(1, 1, 3);
Circle circle2 = circle1.copy();
System.out.println
(circle1.getX()+
", " +
circle1.getY() + ", "
+ circle1.getR());
System.out.println
(circle2.getX()+
", " +
circle2.getY() + ", "
+ circle2.getR());
}
}
참고
https://copynull.tistory.com/127
http://knowledgebase.oasissofttech.com/index.php?title=Prototype_Design_Pattern
소스코드
https://github.com/garam-park/java-designpattern
'Java > design pattern' 카테고리의 다른 글
[java] 7강 빌더 패턴(Builder Pattern) (0) | 2020.02.03 |
---|---|
[java] 5강 싱글톤 패턴(singleton pattern) (0) | 2020.01.22 |
[java] 4강 팩토리 메소드 패턴(Factory Pattern) (0) | 2020.01.22 |
[java] 3강 템플릿 메소드 패턴(Template Method Pattern) (0) | 2020.01.13 |
[java] 2강 어댑터 패턴(adapter pattern) (0) | 2020.01.13 |