[자바 디자인패턴 소스코드] Strategy Pattern

전략패턴


/**
 * [자바 객체지향 디자인 패턴 - 전략패턴]
 * 같은 문제를 해결하는 여러 알고리즘이 클래스별로 캡슐화되어 있고
 * 이들이 필요할 때 교체할 수 있도록 함으로써
 * 동일한 문제를 다른 알고리즘으로 해결할 수 있게 하는 디자인 패턴이다.
 * @author JHS
 *
 */
public class Strategy {

    public static void main(String[] args) {
        Robot dagan = new Dagan("다간");
        Robot gundam = new Gundam("건담");

        dagan.setMovingStrategy(new WalkingStrategy());
        dagan.setAttackStrategy(new MissileStrategy());

        gundam.setMovingStrategy(new FlyingStrategy());
        gundam.setAttackStrategy(new PunchStrategy());

        System.out.println("My name is " + dagan.getName());
        dagan.move();
        dagan.attack();

        System.out.println();

        System.out.println("My name is " + gundam.getName());
        gundam.move();
        gundam.attack();
    }
}

interface MovingStrategy {
    public void move();
}
interface AttackStrategy {
    public void attack();
}

abstract class Robot {
    private String name;
    private MovingStrategy movingStrategy;
    private AttackStrategy attackStrategy;

    public Robot(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void move() {
        movingStrategy.move();
    }

    public void attack() {
        attackStrategy.attack();
    }

    public void setMovingStrategy(MovingStrategy movingStrategy) {
        this.movingStrategy = movingStrategy;
    }

    public void setAttackStrategy(AttackStrategy attackStrategy) {
        this.attackStrategy = attackStrategy;
    }
}

class Gundam extends Robot {

    public Gundam(String name) {
        super(name);
    }
}

class Dagan extends Robot {

    public Dagan(String name) {
        super(name);
    }
}

class FlyingStrategy implements MovingStrategy {
    public void move() {
        System.out.println("I can fly");
    }
}

class WalkingStrategy implements MovingStrategy {
    public void move() {
        System.out.println("I can only walk.");
    }
}

class MissileStrategy implements AttackStrategy {
    public void attack() {
        System.out.println("I have Missile and can attack with it.");
    }
}

class PunchStrategy implements AttackStrategy {
    public void attack() {
        System.out.println("I have strong punch and can attack with it.");
    }
}

참고도서: JAVA 객체지향 디자인 패턴 - 정인상저

이 글을 공유하기

댓글

Designed by JB FACTORY