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

데코레이터 패턴

/**
 * [데코레이터 패턴]은 기본 기능에 추가할 수 있는 많은 종류의 부가 기능에
 * 파생되는 다양한 조합을 동적으로 구현할 수 있는 패턴이다.
 */
public class DecoratorPattern {
    public static void main(String[] args) {

        Aircraft fighterPlane =
                new LaserDecorator(
                        new FireballDecorator(
                                new MissileDecorator(
                                        new NormalAttack())));
        fighterPlane.attack();
    }
}

abstract class Aircraft {
    public abstract void attack();
}

class NormalAttack extends Aircraft {
    public void attack() {
        System.out.println("일반공격");
    }
}

abstract class AirCraftDecorator extends Aircraft {
    private Aircraft decoratedAircraft;

    public AirCraftDecorator(Aircraft decoratedAircraft) {
        this.decoratedAircraft = decoratedAircraft;
    }

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

class MissileDecorator extends AirCraftDecorator {
    public MissileDecorator(Aircraft decoratedAircraft) {
        super(decoratedAircraft);
    }

    public void attack() {
        super.attack();
        missileAttack();
    }

    private void missileAttack() {
        System.out.println("    미사일 공격");
    }
}

class FireballDecorator extends AirCraftDecorator {
    public FireballDecorator(Aircraft decoratedAircraft) {
        super(decoratedAircraft);
    }

    public void attack() {
        super.attack();
        fireballAttack();
    }

    private void fireballAttack() {
        System.out.println("    파이어볼 공격");
    }
}

class LaserDecorator extends AirCraftDecorator {
    public LaserDecorator(Aircraft decoratedAircraft) {
        super(decoratedAircraft);
    }

    public void attack() {
        super.attack();
        laserAttack();
    }

    private void laserAttack() {
        System.out.println("    레이저 공격");
    }
}

이 글을 공유하기

댓글

Designed by JB FACTORY