자바 디자인 패턴
*6. Prototype - 복사해서 인스턴스를 만든다
조요피
2023. 10. 9. 21:07
6. Prototype - 복사해서 인스턴스를 만든다
클래스에서 인스턴스를 생성하는 대신 인스턴스로부터 다른 인스턴스를 생성하는 Prototype 패턴.
다음과 같은 경우에는 클래스로부터 인스턴스를 만드는 대신 인스턴스를 복사해서 새 인스턴스를 만든다.
1. 종류가 너무 많아 클래스로 정리할 수 없는 경우
취급할 오브젝트가 너무 많아서, 하나하나 다른 클래스로 만들면 소스 파일을 많이 작성해야 하는 경우
2. 클래스로부터 인스턴스 생성이 어려운 경우
생성하고 싶은 인스턴스가 복잡한 과정을 거쳐 만들어지는 경우
3. 프레임워크와 생성하는 인스턴스를 분리하고 싶은 경우
인스턴스를 생성하는 프레임워크를 특정 클래스에 의존하지 않게 하고 싶은 경우
이런 경우에는 클래스 이름을 지정해서 인스턴스를 만드는 것이 아니라
미리 원형이 될 인스턴스를 등록해 두고 등록된 인스턴스를 복사해서 사용
예제
import framework.Manager;
import framework.Product;
public class Main {
public static void main(String[] args) {
// 준비
Manager manager = new Manager();
UnderlinePen upen = new UnderlinePen('-');
MessageBox mbox = new MessageBox('*');
MessageBox sbox = new MessageBox('/');
// 등록
manager.register("strong message", upen);
manager.register("warning box", mbox);
manager.register("slash box", sbox);
// 생성과 사용
Product p1 = manager.create("strong message");
p1.use("Hello, world.");
Product p2 = manager.create("warning box");
p2.use("Hello, world.");
Product p3 = manager.create("slash box");
p3.use("Hello, world.");
}
}
package framework;
import java.util.HashMap;
import java.util.Map;
public class Manager {
private Map<String, Product> showcase = new HashMap<>();
public void register(String name, Product prototype) {
showcase.put(name, prototype);
}
public Product create(String prototypeName) {
Product p = showcase.get(prototypeName);
return p.createCopy();
}
}
package framework;
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createCopy();
}
import framework.Product;
public class MessageBox implements Product {
private char decochar;
public MessageBox(char decochar) {
this.decochar = decochar;
}
@Override
public void use(String s) {
int decolen = 1 + s.length() + 1;
for (int i = 0; i < decolen; i++) {
System.out.print(decochar);
}
System.out.println();
System.out.println(decochar + s + decochar);
for (int i = 0; i < decolen; i++) {
System.out.print(decochar);
}
System.out.println();
}
@Override
public Product createCopy() {
Product p = null;
try {
p = (Product) clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
import framework.Product;
public class UnderlinePen implements Product {
private char ulchar;
public UnderlinePen(char ulchar) {
this.ulchar = ulchar;
}
@Override
public void use(String s) {
int ulen = s.length();
System.out.println(s);
for (int i = 0; i < ulen; i++) {
System.out.print(ulchar);
}
System.out.println();
}
@Override
public Product createCopy() {
Product p = null;
try {
p = (Product) clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}