ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [생성 패턴] Prototype
    CS/디자인패턴 2021. 5. 20. 17:51

     

    생성 패턴 중 Prototype Pattern(프로토타입 패턴)에 대해서 알아보자.

    1. Prototype Pattern

     

    프로토타입의 핵심 아이디어

    기존에 존재하는 인스턴스를 복사해서 새 인스턴스를 만들자

     

    예를 들어서, A라는 사람이 디자인 패턴에 대해 잘 정리한 파일(ex_ A.hwp)을 갖고 있다고 해보자. 이 파일을 A의 친구인 B와 C가 달라고 한다. 이때 A는 원본 파일을 주게 되면, B와 C에 의해서 A.hwp가 훼손될 가능성이 있기 때문에 새로운 파일을 만들어서 주려고 할 것이다. 그렇다면 아래의 두 가지 방법이 있다.

    • 새 한글 문서를 키고 A.hwp의 내용을 타이핑하여 새 파일을 만들고, 이를 B와 C에게 준다.
    • A.hwp를 Ctrl C, V를 해서 새 파일을 만들고, 이를 B와 C에게 준다.

     

    A의 입장에서 두 방법 중 어떤 방법이 효율적일까. 당연히 두 번째 방법일 것이다.

     

    새로운 객체를 생성하는 과정도 마찬가지다. 아예 밑바닥에서 시작하여 만들어내는 것보다. 기존에 참조할 수 있는 인스턴스가 있다면 이를 복사해서 필요한 부분만 수정하는 것이 시간과 자원 측면에서 뛰어나다.

     

    2. Stucture

    프로토타입의 구조는 간단한 편에 속한다.

     

    구상 클래스가 clone()이라는 공통의 인터페이스를 갖도록 설정해주고, clone()을 구현하여 갖고 있으면 된다.

     

    3. Example

    Java 코드를 통해서 프로토타입 패턴을 살펴보자.

     

    예제로 만들어볼 것은 위에서 이야기했던 A가 자신이 갖고 있는 내용을 B 또는 C에게 전달해야 하는 상황을 간략화하여 만들어 볼 것이다.

     

    Java에 존재하는 Cloneable이라는 인터페이스를 사용하여 명시적으로 Prototype 인터페이스를 작성하였다.

    public interface Prototype extends Cloneable {
    	public DesignPattern clone() throws CloneNotSupportedException;
    }

    DesignPattern에 대한 정보(이름, 설명)을 갖고 있는 클래스를 아래와 같이 만들 수 있다.

    public class DesignPattern implements Prototype {
    	private String name;
    	private String des;
        
    	public DesignPattern (String name, String des) {
    		this.name = name;
    		this.des = des;
    	}
        
    	@Override
    	public DesignPattern clone() {
    		try {
    			return (DesignPattern) super.clone();
    		} catch (CloneNotSupportedException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
        
    	public String getName() { return this.name; }
    	public String getDes() { return this.des; }
    	public void setDes(String des) { this.des = des; }
        
        @Override
        public String toString() {
        	return "Name: " + name + ", Description: " + des;
        }
    }

    이제 A가 정리한 디자인 패턴에 대한 내용을 담고 있는 클래스 SummaryDesignPattern을 만들어보자.

    public class SummaryDesignPattern {
    	private static Map<String, DesignPattern> = new HashMap<String, DesignPattern>();
        
    	static {
    		map.put("Factory", new DesignPattern("Factory", "Factory Description..."));
    		map.put("AbstractFactory", new DesignPattern("AbstractFactory", "AbstractFactory Description..."));
    		map.put("Prototype", new DesignPattern("Prototype", "Prototype Description..."));
    		// ...
    	}
        
    	public static DesignPattern getDesignPattern(String name) {
    		DesignPattern dp = null;
    		dp = map.get(name);
    		if (dp != null) {
    			return dp.clone();
    		}
    		return null
    	}
    }

    이 코드에서의 핵심은 getDesignPattern()에서 인스턴스를 단순히 clone()을 통해 반환한다는 것이다. 이와 같이 구현하지 않았다면, 해당 인스턴스의 내용을 알아내기 위해서 getName()와 getDes()를 호출하는 부차적인 과정이 필요했을 것이다.

     

    최종적으로 B 또는 C가 A가 정리한 패턴의 내용을 요청하는 상황을 아래처럼 만들어 볼 수 있다.

    public class testPrototypePattern {
    	public static void main(String[] args) {
        	DesignPattern factoryPattern = SummaryDesignPattern.getDesignPattern("Factory");
            System.out.println(factoryPattern);
            
            System.out.println("=======================");
            
            DesignPattern PrototyePattern = SummaryDesignPattern.getDesignPattern("Prototype");
            System.out.println(PrototyePattern);
        }
    }

    임의의 어떤 사람이 Factory와 Prototype 패턴에 대한 자료를 요청했고 SummaryDesignPattern 클래스에서는 해당 인스턴스들을 단순히 복사하여 주는 것으로 간단하게 처리한 코드이다.

     

    위 코드의 결과는 아래와 같다. 원하는 내용이 담긴 인스턴스가 제대로 반환된 것을 확인할 수 있다.

    Name: Factory, Description: Factory Description...
    =======================
    Name: Prototype, Description: Prototype Description...

     

    만약, 프로토타입 패턴을 활용하지 않았다면, 인스턴스를 새로 만들고, 기존 인스턴스의 내용을 하나씩 읽어서 새로 만든 인스턴스에 입력하는 과정이 필요하다는 것을 다시 한번 강조한다.

    References

    - Rohit Joshi. 2015. "Java Design Pattern". Java Code Geeks

    - https://refactoring.guru/design-patterns/prototype. accessed 2021.05.20

    'CS > 디자인패턴' 카테고리의 다른 글

    [생성 패턴] Singleton  (0) 2021.05.25
    [생성 패턴] Builder  (0) 2021.05.21
    [생성 패턴] Abstract Factory Method  (0) 2021.05.19
    [생성 패턴] Factory Method  (0) 2021.05.18
    [디자인 패턴] 개요  (0) 2021.05.17

    댓글

Designed by Tistory.