프로토타입 패턴

Lee·2023년 4월 25일
0

디자인 패턴

목록 보기
4/7

프로토타입 패턴

  • 객체에 의해 생성될 객체의 타입이 결정되는 생성 디자인 패턴
  • 원본 객체를 새로운 객체에 복사하여 필요에 따라 수정

구현

코드 출처 : Baeldung - Prototype Pattern in Java

public abstract class Tree {
    private double mass;
    private double height;
    private Position position;

    public Tree(double mass, double height) {
        this.mass = mass;
        this.height = height;
    }

    public double getMass() {
        return mass;
    }

    public void setMass(double mass) {
        this.mass = mass;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public Position getPosition() {
        return position;
    }

    public void setPosition(Position position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "Tree{" +
                "mass=" + mass +
                ", height=" + height +
                ", position=" + position +
                '}';
    }

    public abstract Tree copy();
}
public final class Position {
    private final int x;
    private final int y;

    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Position other = (Position) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 13;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }

    @Override
    public String toString() {
        return "Position{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}
public class PineTree extends Tree{
    private String type;

    public PineTree(double mass, double height) {
        super(mass, height);
        this.type = "Pine";
    }

    public String getType() {
        return type;
    }

    @Override
    public Tree copy() {
        PineTree pineTreeClone = new PineTree(this.getMass(), this.getHeight());
        pineTreeClone.setPosition(this.getPosition());
        return pineTreeClone;
    }
}
public class PlasticTree extends Tree{
    private String name;

    public PlasticTree(double mass, double height) {
        super(mass, height);
        this.name = "PlasticTree";
    }

    public String getName() {
        return name;
    }

    @Override
    public Tree copy() {
        PlasticTree plasticTreeClone = new PlasticTree(this.getMass(), this.getHeight());
        plasticTreeClone.setPosition(this.getPosition());
        return plasticTreeClone;
    }
}

사용 이유

  1. 종류가 너무 많아 클래스로 정리되지 않는 경우
    • 취급하는 객체의 종류가 너무 많아서 각각을 별도의 클래스로 만들어 다수의 소스 파일을 작성해야 하는 경우.
  2. 클래스로부터 인스턴스 생성이 어려운 경우
    • 생성하고자 하는 인스턴스가 복잡한 작업을 거쳐 만들어지기 때문에 클래스로부터 만들기가 매우 어려운 경우.
  3. 복사하려는 클래스의 정보를 캡슐화 가능
    • 객체 복사 중 위 코드의 Tree 클래스의 구성요소를 알 수 없으나 copy 메서드 호출 시 프로그램이 실제 클래스 확인 후 적절한 복제 메서드 실행
  4. 객체 생성 역할의 별도의 클래스 불필요

단점

  1. 순환 참조가 있는 객체의 복사 어려움

참고
Prototype Pattern in Java
프로토타입 패턴

profile
발전하고 싶은 백엔드 개발자

0개의 댓글