design pattern #4 Creational pattern - Prototype

  •  prototyping 이란,  간단하게 보면 java에서의 clone 하는것을 말한다. cloneable interface 를 구현한 모든 class  를 clone 하여 복제 할 수 있다
  • 그러면 copy 하고 싶을때 일일히 모든 field 를 찾아서 set 하지 않아도 되고, private field 나  abstract 객체를 신경쓰지 않아도 된다. 그리고 대상 class 에 대해 자세히 알지 않아도 되므로, 복사하려는 class 가 바뀌거나 하더라도 사용하는 쪽에서 문제되지 않는다. 
  • 이렇게 clone 된 객체는 동일하진 않으나 (a!=a'),  identical 하다 (a.equals(a')). 

  • cloneable 을 implement 하지 않는 경우엔, clone 메소드를 직접 만들 수 있다. 
  • 구체 class 의 @Override clone() 메소드의 return type 이 abstract 타입인 것에 주목한다.
public abstract class Shape {

    public int x;
public int y;
public String color;

public Shape() {
}

public Shape(Shape target) {
if (target != null) {
this.x = target.x;
this.y = target.y;
this.color = target.color;
}
}

public abstract Shape clone();

@Override
public boolean equals(Object object2) {
if (!(object2 instanceof Shape)) return false;
Shape shape2 = (Shape) object2;
return shape2.x == x && shape2.y == y && Objects.equals(shape2.color, color);
}
}


public class Circle extends Shape {
public int radius;

public Circle(Circle target) {
super(target);
if (target != null) {
this.radius = target.radius;
}
}

@Override
public Shape clone() {
return new Circle(this);
}

@Override
public boolean equals(Object object2) {
if (!(object2 instanceof Circle) || !super.equals(object2)) return false;
Circle shape2 = (Circle) object2;
return shape2.radius == radius;
}
}


public class Rectangle extends Shape {
public int width;
public int height;

public Rectangle(Rectangle target) {
super(target);
if (target != null) {
this.width = target.width;
this.height = target.height;
}
}

@Override
public Shape clone() {
return new Rectangle(this);
}

@Override
public boolean equals(Object object2) {
if (!(object2 instanceof Rectangle) || !super.equals(object2)) return false;
Rectangle shape2 = (Rectangle) object2;
return shape2.width == width && shape2.height == height;
}
}

Comments

Popular posts from this blog

삼성전자 무선사업부 퇴사 후기

코드리뷰에 대하여

개발자 커리어로 해외 취업, 독일 이직 프로세스