'Strategy'에 해당되는 글 1건

  1. 스트래티지 패턴(Strategy Pattern)

스트래티지 패턴(Strategy Pattern)






스트래티지 패턴(Strategy pattern) 에서는 알고리즘군을 정의하고 각각을 캡슐화하여 교환해서 사용할 수 있도록 만든다.
스트래티지를 활용하면 알고리짐을 사용하는 클라이언트와는 독립적으로 알고리즘을 변경할수있다.


package org.acounta.strategy;
public abstract class Duck {
 FlyBehavior flyBehavior;
 QuackBehavior quackbehavior;

 public Duck() {
 }
 public abstract void display();

 public void performFly() {
  flyBehavior.fly();
 }
 public void performQuack(){
  quackbehavior.quack();
 }

 public void swim(){
  System.out.println("모든 오리는 물에 뜸");
 }

}

----------------------------------------------------------------

package org.acounta.strategy;

public interface FlyBehavior {

 void fly();

}

----------------------------------------------------------------

package org.acounta.strategy;

public class FlyNoWay implements FlyBehavior {

 @Override
 public void fly() {
  System.out.println("i'm not flying");
 }

}

----------------------------------------------------------------

package org.acounta.strategy;

public class FlyWithWings implements FlyBehavior {

 @Override
 public void fly() {
  System.out.println("i'm flying");
 }

}


----------------------------------------------------------------

package org.acounta.strategy;

public class MallardDuck extends Duck {
 public MallardDuck(){
  quackbehavior = new Quack();
  flyBehavior = new FlyWithWings();
 }
 
 @Override
 public void display() {
  System.out.println("i'm water duck");
 }

}

----------------------------------------------------------------

package org.acounta.strategy;

public class MuteQuack implements QuackBehavior {

 @Override
 public void quack() {
  System.out.println("닥쳐!");
 }

}

----------------------------------------------------------------

package org.acounta.strategy;

public class Quack implements QuackBehavior {

 @Override
 public void quack() {

  System.out.println("Quack");
 }

}


----------------------------------------------------------------

package org.acounta.strategy;

public interface QuackBehavior {

 void quack();

}

----------------------------------------------------------------

package org.acounta.strategy;

public class Squack implements QuackBehavior {

 @Override
 public void quack() {
  System.out.println("삑");
 }

}
----------------------------------------------------------------

package org.acounta.strategy;

public class AcountaTestMain{
 public static void main(String[] args) {
  Duck mallard = new MallardDuck();
  mallard.performFly();
  mallard.performQuack();
  mallard.swim();
 }
}

i'm flying
Quack
모든 오리는 물에 뜸