public abstract class Robot {
private String name;
public Robot(String name) {
this.name = name;
}
public abstract void move();
public abstract void attack();
}
public class TaekwonV extends Robot{
public TaekwonV(String name) {
super(name);
}
@Override
public void move() {
System.out.println("I can only walk");
}
@Override
public void attack() {
System.out.println("I have Missile and can attack with it");
}
}
public class Atom extends Robot{
public Atom(String name) {
super(name);
}
@Override
public void move() {
System.out.println("I have strong punch and can attack with it");
}
@Override
public void attack() {
System.out.println("I can fly");
}
}
b. 문제점
c. 해결책
public abstract class Robot {
private AttackMode attackMode;
private MoveMode moveMode;
private String name;
Robot(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAttackMode(AttackMode mode){
this.attackMode = mode;
}
public void setMoveMode(MoveMode mode){
this.moveMode = mode;
}
public void attack(){
attackMode.attack();
}
public void move(){
moveMode.move();
}
}
class Atom extends Robot{
Atom(String name) {
super(name);
attackMode = new FistMode();
moveMode = new FlyMode();
}
}
class TaekwonV extends Robot{
TaekwonV(String name){
super(name);
attackMode = new MissileMode();
moveMode = new WalkMode();
}
}
class Sungard extends Robot{
Sungard(String name){
super(name);
this.attackMode = new MissileMode();
this.moveMode = new WalkMode();
}
}
public interface AttackMode {
public void attack();
}
class FistMode implements AttackMode {
@Override
public void attack() {
System.out.println("주먹 공격");
}
}
class MissileMode implements AttackMode {
@Override
public void attack() {
System.out.println("미사일 공격!");
}
}
public interface MoveMode {
public void move();
}
class WalkMode implements MoveMode{
@Override
public void move() {
System.out.println("걸어서 이동");
}
}
class FlyMode implements MoveMode{
@Override
public void move() {
System.out.println("날아서 이동");
}
}
d. 전략 패턴 연습하기.