Eddie's Blog

[design pattern] Prototype Pattern 본문

programmings

[design pattern] Prototype Pattern

eddie.y 2019. 3. 28. 21:02

유형: 생성자 패턴

다양한 객체를 생성하기 위해 Prototypical(prototype을 구현한) 인스턴스를 사용하고, 이 Prototype의 복제를 통해 새로운 객체를 생성한다.

// prototype
public abstract class PlayableContent implements Cloneable {
    public abstract void play();

    @Override
    protected Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

// concrete prototypes
public class Movie extends PlayableContent {
    private String title;

    public Movie(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public void play() {
        System.out.println(String.format("Movie (%s) plays", this.title));
    }

    @Override
    public PlayableContent clone() {
        System.out.println("Cloning Movie...");
        return (Movie) super.clone();
    }
}

public class Song extends PlayableContent {
    private String title;

    public Song(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public void play() {
        System.out.println(String.format("Song (%s) plays", this.title));
    }

    @Override
    public PlayableContent clone() {
        System.out.println("Cloning Song...");
        return (Song) super.clone();
    }
}

// container
public class Player {
    private static Map<String, PlayableContent> contents = new HashMap<String, PlayableContent>() {{
        put("movie", new Movie("Back to the future"));
        put("song", new Song("Billie Jean"));
    }};

    public static PlayableContent getContent(String contentType) {
        return (PlayableContent) contents.get(contentType).clone();
    }
}

// test
public class Test {
    public static void main(String[] args) {
        PlayableContent content = Player.getContent("song");
        content.play();
        //Cloning Song...
		//Song (Billie Jean) plays
    }
}
Comments