2011年2月27日

Strategy Pattern(策略模式)

  • Definition
  • The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
    
  • Class Diagram
  • Strategy Role
  • public interface Strategy {
        public void doSomething();
    }
    
  • ConcreteStrategy Role
  • public class ConcreteStrategy1 implements Strategy {
        public void doSomething(){
            System.out.println(“ConcreteStrategy1’s algorithm”);
        }
    }
    public class ConcreteStrategy2 implements Strategy {
        public void doSomething(){
            System.out.println(“ConcreteStrategy2’s algorithm”);
        }
    }
    
  • Context Role
  • public class Context {
        private Strategy _strategy;
        
        public Context(Strategy strategy){
            this._strategy= strategy;
        }
    
        public performDoSomething(){
            this._strategy.doSomething();
        }
    }
    
  • Client Role
  • public class Client {
        Strategy strategy = new ConcreteStrategy1();
        Context context = new Context(strategy);
        context.performDoSomething();
    }
    

沒有留言:

張貼留言