-
생성 패턴(Creational Pattern) - 프로토타입(Prototype) 패턴Java/디자인패턴 2024. 11. 23. 12:14반응형
프로토타입(Prototype) 패턴은 생성 패턴(Creational Pattern) 중 하나로, 객체의 복사본을 생성할 수 있는 메커니즘을 제공합니다. 이 패턴은 객체를 복제하여 새 객체를 만드는 방식으로, 객체 생성에 드는 비용을 줄이고, 객체가 복잡한 구조를 가질 때 유용합니다. 즉, 새로운 객체를 만들 때 객체의 생성과 초기화 과정이 복잡할 경우, 기존 객체를 복사하여 사용하는 방법을 제시합니다.
1. 프로토타입 패턴의 목적
프로토타입 패턴은 객체를 새로 생성하는 대신, 기존 객체를 복제하여 새로운 객체를 생성하는 방식으로 성능을 개선할 수 있습니다. 이 패턴을 사용하면 객체 생성 시 필요한 시간이 단축되고, 복잡한 객체를 만드는 과정에서 발생할 수 있는 오류를 줄일 수 있습니다.
2. 프로토타입 패턴의 구성 요소
- Prototype 인터페이스: 객체를 복제할 수 있는 clone() 메서드를 정의합니다. 모든 프로토타입 객체는 이 인터페이스를 구현해야 합니다.
- ConcretePrototype 클래스: Prototype 인터페이스를 구현하며, 자신을 복제할 수 있는 구체적인 클래스를 나타냅니다.
- 클라이언트(Client): 클라이언트는 프로토타입을 기반으로 새로운 객체를 생성할 수 있습니다.
3. 프로토타입 패턴의 예제 (Java)
예를 들어, 다양한 유형의 문서를 생성하는 시스템을 생각해 봅시다. 문서 객체는 텍스트, 이미지 등 여러 요소를 포함하고 있으며, 이를 복제하여 여러 종류의 문서를 빠르게 만들 수 있습니다.
코드 예제
// Prototype 인터페이스 interface Document extends Cloneable { Document clone(); // 객체를 복제하는 메서드 void show(); } // ConcretePrototype 클래스: TextDocument class TextDocument implements Document { private String content; public TextDocument(String content) { this.content = content; } @Override public Document clone() { try { return (Document) super.clone(); // 얕은 복제 } catch (CloneNotSupportedException e) { return null; } } @Override public void show() { System.out.println("텍스트 문서 내용: " + content); } } // ConcretePrototype 클래스: ImageDocument class ImageDocument implements Document { private String imagePath; public ImageDocument(String imagePath) { this.imagePath = imagePath; } @Override public Document clone() { try { return (Document) super.clone(); // 얕은 복제 } catch (CloneNotSupportedException e) { return null; } } @Override public void show() { System.out.println("이미지 문서 경로: " + imagePath); } } // 클라이언트 코드 public class PrototypePatternExample { public static void main(String[] args) { Document textDocument = new TextDocument("Hello, Prototype Pattern!"); Document clonedTextDocument = textDocument.clone(); // 텍스트 문서 복제 clonedTextDocument.show(); // 텍스트 문서 내용: Hello, Prototype Pattern! Document imageDocument = new ImageDocument("/images/sample.jpg"); Document clonedImageDocument = imageDocument.clone(); // 이미지 문서 복제 clonedImageDocument.show(); // 이미지 문서 경로: /images/sample.jpg } }
코드 설명
- Document 인터페이스는 clone() 메서드를 정의하여 객체를 복제할 수 있게 합니다.
- TextDocument와 ImageDocument는 Document 인터페이스를 구현하고, 각 객체를 복제할 수 있도록 clone() 메서드를 구현합니다.
- 클라이언트 코드에서는 TextDocument와 ImageDocument 객체를 생성한 후, clone() 메서드를 사용해 객체를 복제합니다.
4. 프로토타입 패턴의 장점과 단점
장점
- 객체 생성 비용이 높은 경우, 객체를 복제하여 생성하는 방식이 효율적입니다.
- 객체의 생성 방식을 클라이언트에서 제어할 수 있어 유연성이 높습니다.
- 객체의 복제를 통해 동일한 구조를 가진 객체들을 빠르게 생성할 수 있습니다.
단점
- 객체 복제 시 깊은 복제(Deep Copy)가 필요한 경우, 복잡한 구조를 다루기 어려울 수 있습니다.
- clone() 메서드를 사용하는 방식은 자바의 기본 제공 Cloneable 인터페이스에 의존하기 때문에, 일부 객체에서 이 메서드 사용을 제대로 구현하지 않으면 예기치 않은 오류가 발생할 수 있습니다.
5. 프로토타입 패턴의 사용 예시
- 객체의 상태가 복잡하고, 새로운 객체를 생성하는 데 비용이 많이 드는 경우 (예: 게임 캐릭터, 그래픽 디자인에서 복잡한 객체 복제)
- 동일한 구조를 가진 객체들이 많이 필요한 경우 (예: 문서 템플릿을 사용해 여러 문서를 빠르게 생성하는 경우)
반응형'Java > 디자인패턴' 카테고리의 다른 글
구조(Structural) 패턴 - 복합체(Composite) 패턴 (0) 2024.11.26 패턴은 행동(Behavioral) - 책임 연쇄(Chain of Responsibility) 패턴 (0) 2024.11.24 행동(Behavioral) - 메멘토(Memento) 패턴 (0) 2024.11.22 행동(Behavioral) - 커맨드(Command) 패턴 (0) 2024.11.21 구조 패턴(Structural Pattern) - 데코레이터(Decorator) 패턴 (0) 2024.11.20