팩토리 메서드 패턴?
- 팩토리 메소드 패턴을 이용하면 클래스의 인스턴스를 만드는 일을 서브 클래스에게 맡기는 것
체스 유닛을 통한 팩토리 메서드 패턴 연습
- 상속을 통해 유닛 클래스간(Pawn, Knight..etc) 관계를 생성
- 팩토리 클래스에서 인스턴스 생성을 담당하도록 했다.
Piece 클래스
public class Piece {
private final UnitColor color;
public Piece(UnitColor color) {
this.color = color;
}
public boolean isColor(UnitColor color) {
return this.getColor().equals(color);
}
public UnitColor getColor() {
return color;
}
public char getRepresentation() {
return UnitType.getMark(this.color, this.getClass().getSimpleName());
}
}
Pawn 클래스
public class Pawn extends Piece {
public Pawn(UnitColor color) {
super(color);
}
}
UnitType 열거형
public enum UnitType {
PAWN('P'),
ROOK('R'),
KNIGHT('N'),
BISHOP('B'),
QUEEN('Q'),
KING('K'),
NONE('.');
private final char unitRepresentation;
UnitType(char mark) {
this.unitRepresentation = mark;
}
public static char getMark(UnitColor color, String unitClassName) {
char mark = ' ';
switch (color) {
case BLACK:
mark = Character.toUpperCase(UnitType.valueOf(unitClassName.toUpperCase()).unitRepresentation);
break;
case WHITE:
mark = Character.toLowerCase(UnitType.valueOf(unitClassName.toUpperCase()).unitRepresentation);
break;
}
return mark;
}
}
PieceFactory 클래스
- 팩토리 메서드 패턴을 적용 해보았는데, 잘한건지 잘모르겠습니다.
- 사실 createWhite, createBlack 메소드는 하나임.
- 매게변수를 줄이고 메서드 이름을 통해 가독성을 향상 시키고자 중복을 감안하고 두개로 분리 했음.
public class PieceFactory {
public Piece createWhite(UnitType unitType) {
Piece piece = null;
final UnitColor WHITE = UnitColor.WHITE;
switch (unitType) {
case KNIGHT:
piece = new Knight(UnitColor.WHITE);
break;
case PAWN:
piece = new Pawn(UnitColor.WHITE);
break;
}
return piece;
}
public Piece createBlack(UnitType unitType) {
Piece piece = null;
switch (unitType) {
case KNIGHT:
piece = new Knight(UnitColor.BLACK);
break;
case PAWN:
piece = new Pawn(UnitColor.BLACK);
break;
}
return piece;
}
}
테스트
- 원하던 결과가 나오긴 했는데, 잘한건지는 모르겠다.
public class APP {
public static void main(String[] args) {
PieceFactory pieceFactory = new PieceFactory();
Piece pawn = pieceFactory.createBlack(UnitType.PAWN);
Piece pawn2 = pieceFactory.createWhite(UnitType.PAWN);
Piece knight = pieceFactory.createWhite(UnitType.KNIGHT);
System.out.println(pawn.getRepresentation());
System.out.println(pawn2.getRepresentation());
System.out.println(knight.getRepresentation());
}
}
책임에 대한 고민
- 각 유닛 마다 좌표 정보의
상태
를 구현해줄 것인지
- 체스 보드객체가 객체들의 좌표정보를 담당 할지
느낀점
- 오늘 하루 팩토리 메소드 패턴이 어제 공부했던
깊은복제
의 방법중 복사 생성자 또는 복사 팩토리
의 연장공부여서 재밌게 한 것 같다.
- 작업을 하다가 깃을 잘못 다뤄서 작업중인 프로젝트 폴더가 통째로 날아간 적이 있는데 진짜 정말 무서웠다. 결과적으로 reflog와 git reset을 통해 복구할 수 있었는데 혼자서 문제를 해결했다는게 뭔가 뿌듯하고 앞으로 git 공부를 열심히 해야할 것 같다.
- 추가적인 공부를 못한 하루이지만 팩토리 메소드 패턴 하나를 알았고 활용한 것은 큰 수확이라고 생각한다. 내일도 열심히 달리자!