Prototype Pattern

정의
클래스로부터 인스턴스를 만드는 것이 아니고, 인스턴스에서 새로운 인스턴스를 만든다.(복사해서 사용)

Prototype
인스턴스를 복사하여 새로운 인스턴스를 만들기 위한 메소드를 결정하는 클래스

ConcretePrototype
인스턴스를 복사해서 새로운 인스턴스를 만드는 메소드를 실제로 구현한 클래스

Client
인스턴스를 복사하는 메소드를 이용해서 새로운 인스턴스를 만든다.

언제 Prototype 패턴을 사용하나?
1. 종류가 너무 많아서 클래스로 정리할 수 없는 경우
2. 클래스로부터 인스턴스 생성이 어려운 경우
3. framework와 생성하는 인스턴스를 분리하고 싶은 경우





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

public 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 Manager {
	private HashMap showcase = new HashMap();
	
	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();
	}
}

public class Main {
	public static void main(String[] args) {
		Manager manager = new Manager();
		MessageBox mbox = new MessageBox('*');
		MessageBox sbox = new MessageBox('/');
		manager.register("strong message", mbox);
		manager.register("slash box", sbox);
		
		Product p1 = manager.create("strong message");
		p1.use("Hello world");
		Product p2 = manager.create("slash box");
		p2.use("Hello world");
	}
}




결과 화면
***************
* Hello world *
***************
///////////////
/ Hello world /
///////////////

예제소스 : Java 언어로 배우는 디자인 패턴 입문
Posted by outliers
,