Overview

객체 생성과 관련된 패턴은 겹치는 영역이 있습니다. 프로토타입 패턴이나 추상 팩토리 패턴을 적용할 수 있는 경우가 있습니다.

추상 팩토리 패턴은 프로토타입 세트를 갖고 이를 복제하고 제품 객체를 반환할 수 있습니다.

그런 다음 디자이너의 재량에 따라 추상 팩토리 패턴, 빌더 패턴 또는 프로토타입 패턴으로 변경할 수 있습니다. 프로토타입은 서브클래싱이 필요하지 않습니다.
그러나 "초기화" 작업이 필요합니다. 팩토리 메소드 패턴은 서브클래싱이 필요하지만 "초기화" 작업은 필요하지 않습니다.

디자이너는 복합 패턴이나 데코레이터 패턴을 사용하는 무거운 디자인을 프로토타입으로 훨씬 더 잘 만들 수 있습니다.

원칙은 "런타임"에 다른 "객체"를 생성한다는 것입니다.
즉, 이 시점에서 복제되는 개체의 "실제 복사본"이 만들어집니다.

"실제 사본"이라는 용어는 새로 생성된 개체가 복제된 개체의 속성과 동일한 속성을 가짐을 의미합니다.

반면에 "new"를 사용하여 객체를 생성하는 경우 새로 생성된 객체의 속성은 초기 값을 갖습니다.

장점
객체를 생성하기 위해 별도의 객체 생성 클래스가 필요하지 않습니다. 개체의 각 부분을 결합하여 만든 형태에도 적용할 수 있습니다.

단점
생성하고자 하는 객체의 데이터 타입인 모든 클래스는 clone() 메소드를 구현해야 한다.

 

Structure

https://ko.wikipedia.org/wiki/%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85_%ED%8C%A8%ED%84%B4

 

Code Example

package com.example.design.pattern;

import java.util.Hashtable;

interface Product extends Cloneable {
	public abstract void use(String s);

	public abstract Product createClone();
}

class Manager {
	private Hashtable showcase = new Hashtable();

	public void register(String name, Product proto) {
		showcase.put(name, proto);
	}

	public Product create(String protoname) {
		Product p = (Product) showcase.get(protoname);
		return p.createClone();
	}
}

class UnderlinePen implements Product {
	private char ulchar;

	public UnderlinePen(char ulchar) {
		this.ulchar = ulchar;
	}

	public void use(String s) {
		int length = s.getBytes().length;
		System.out.println("\"" + s + "\"");
		System.out.print(" ");
		for (int i = 0; i < length; i++) {
			System.out.print(ulchar);
		}
		System.out.println("");
	}

	public Product createClone() {
		Product p = null;
		try {
			p = (Product) clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return p;
	}
}

class MessageBox implements Product {
	private char decochar;

	public MessageBox(char decochar) {
		this.decochar = decochar;
	}

	public void use(String s) {
		int length = s.getBytes().length;
		for (int i = 0; i < length + 4; i++) {
			System.out.print(decochar);
		}
		System.out.println("");
		System.out.println(decochar + " " + s + " " + decochar);
		for (int i = 0; i < length + 4; i++) {
			System.out.print(decochar);
		}
		System.out.println("");
	}

	public Product createClone() {
		Product p = null;
		try {
			p = (Product) clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return p;
	}
}

public class MyPrototype {
	public static void main(String[] args) {
		// 준비
		Manager manager = new Manager();
		UnderlinePen upen = new UnderlinePen('~');
		MessageBox mbox = new MessageBox('*');
		MessageBox sbox = new MessageBox('/');

		UnderlinePen upen2 = new UnderlinePen('%');

		upen.use("Hello, world.");
		System.out.println();
		mbox.use("Hello, world.");
		System.out.println();
		sbox.use("Hello, world.");
		System.out.println();
		upen2.use("Hello, world.");
		System.out.println();

		manager.register("strong message", upen);
		manager.register("warning box", mbox);
		manager.register("slash box", sbox);

		// Prototype으로부터 복제 생성

		Product p1 = manager.create("strong message");
		p1.use("Hello, world.");
		System.out.println();

		Product p2 = manager.create("warning box");
		p2.use("Hello, world.");
		System.out.println();

		Product p3 = manager.create("slash box");
		p3.use("Hello, world.");
		System.out.println();

	}
}

 

Console Result

"Hello, world."
 ~~~~~~~~~~~~~

*****************
* Hello, world. *
*****************

/////////////////
/ Hello, world. /
/////////////////

"Hello, world."
 %%%%%%%%%%%%%

"Hello, world."
 ~~~~~~~~~~~~~

*****************
* Hello, world. *
*****************

/////////////////
/ Hello, world. /
/////////////////

 

Conclusion

N/A

728x90
1234···19
반응형

+ Recent posts