ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 행위패턴 : Strategy 패턴
    디자인패턴 2013. 3. 18. 09:00
    반응형

    분류 : 행위패턴(Behavioral Patterns)


    정의 :

    알고리즘의 동작이 실행시에 결정되는 패턴. 알고리즘의 집합을 정의하고 각각을 캡슐화 한 다음 해당 알고리즘들을 교환가능하게 만듬.

    용도 :

    입력 데이터의 검증을 수행할때 데이터의 타입에 따라 검증 알고리즘을 선택하도록 함.




    소스

    /** The classes that implement a concrete strategy should implement this.
    * The Context class uses this to call the concrete strategy. */
    interface Strategy {
        int execute(int a, int b); 
    }
    
    
    /** Implements the algorithm using the strategy interface */
    class Add implements Strategy {
        public int execute(int a, int b) {
            System.out.println("Called Add's execute()");
            return a + b;  // Do an addition with a and b
        }
    }
    
    
    class Subtract implements Strategy {
        public int execute(int a, int b) {
            System.out.println("Called Subtract's execute()");
            return a - b;  // Do a subtraction with a and b
        }
    }
    
    
    class Multiply implements Strategy {
       public int execute(int a, int b) {
           System.out.println("Called Multiply's execute()");
           return a * b;   // Do a multiplication with a and b
       }    
    }
    
    
    /** Configured with a ConcreteStrategy object and maintains a reference to a Strategy object */
    class Context {
        private Strategy strategy;
     
        public Context(Strategy strategy) {
            this.strategy = strategy;
        }
     
        public int executeStrategy(int a, int b) {
            return strategy.execute(a, b);
        }
    }
     
    
    /** Tests the pattern */
    class StrategyExample {
       public static void main(String[] args) {
           Context context;
    
           // Three contexts following different strategies
           context = new Context(new Add());
           int resultA = context.executeStrategy(3,4);
    
           context = new Context(new Subtract());
           int resultB = context.executeStrategy(3,4);
    
           context = new Context(new Multiply());
           int resultC = context.executeStrategy(3,4);
    
           System.out.println("Result A : " + resultA );
           System.out.println("Result B : " + resultB );
           System.out.println("Result C : " + resultC );
       }
    }
    
    


    참고자료

    http://en.wikipedia.org/wiki/Strategy_pattern

    반응형

    '디자인패턴' 카테고리의 다른 글

    행위패턴 : Visitor 패턴  (0) 2013.03.27
    행위패턴 : Template Method 패턴  (0) 2013.03.25
    행위패턴 : State 패턴  (0) 2013.03.11
    행위패턴 : Observer 패턴  (0) 2013.03.04
    행위패턴 : Memento 패턴  (0) 2013.02.28

    댓글

Designed by Tistory.