*行動型パターン_初めてポリシーモード

1762 ワード

23種類の革新モデル総署の父文リンク親文リンク
  • ポリシーパターンは、一連のアルゴリズムを定義し、それぞれのアルゴリズムをカプセル化し、相互に置換することができ、アルゴリズムの変化は、アルゴリズムを使用するクライアントに影響を与えない.
  • は、一連の実装クラスのための統一的な方法を提供するインターフェースを設計する必要があります.複数の実装クラスがこのインターフェースを実現し、抽象的なクラスを設計し、補助関数を提供します.関係図は以下の通りです.
    策略
    public interface ICalculator {  
        public int calculate(String exp);  
    } 
    public class Plus extends AbstractCalculator implements ICalculator {  
      
        @Override  
        public int calculate(String exp) {  
            int arrayInt[] = split(exp,"\\+");  
            return arrayInt[0]+arrayInt[1];  
        }  
    } 
    public class Minus extends AbstractCalculator implements ICalculator {  
      
        @Override  
        public int calculate(String exp) {  
            int arrayInt[] = split(exp,"-");  
            return arrayInt[0]-arrayInt[1];  
        }  
      
    }
    public class Multiply extends AbstractCalculator implements ICalculator {  
      
        @Override  
        public int calculate(String exp) {  
            int arrayInt[] = split(exp,"\\*");  
            return arrayInt[0]*arrayInt[1];  
        }  
    } 
    
    補助クラス:
    public abstract class AbstractCalculator {  
          
        public int[] split(String exp,String opt){  
            String array[] = exp.split(opt);  
            int arrayInt[] = new int[2];  
            arrayInt[0] = Integer.parseInt(array[0]);  
            arrayInt[1] = Integer.parseInt(array[1]);  
            return arrayInt;  
        }  
    }
    
    使用:
    public class StrategyTest {  
      
        public static void main(String[] args) {  
            String exp = "2+8";  
            ICalculator cal = new Plus();  
            int result = cal.calculate(exp);  
            System.out.println(result);  
        }  
    }
    
    注:個人的な感覚
    この中には、このようなアダプターモードの設計構想が対象のアダプターモードの設計構想に転化することができます.