LoginSignup
8
7

More than 5 years have passed since last update.

Effective Java:Enum編

Last updated at Posted at 2016-02-17

定数固有メソッド実装をもつenum型

public enum Operation{
   PLUS{double calc(double x, double y){return x + y;}},
   MINUS{double calc(double x, double y){return x - y;}},
   TIMES{double calc(double x, double y){return x * y;}},
   DIVIDE{double calc(double x, double y){return x / y;}} 

   abstract double calc(double x, double y);
}

戦略enumパターン

OperationにPLUS{double ~}として処理を記述しているが、
戦略enumに処理を委譲する事もできる。
機能と実装を分離してみる。

public enum Operation{
   PLUS(Strategy.PLUS),

   private Strategy strategy;
   Operation(Strategy strategy){ this.strategy = strategy;}

   double calc(double x , double y){
       return strategy.calc(x,y);
   }
}

public enum Strategy{
  PLUS{double calc(double x, double y){return x + y}},

  abstract double calc(double x, double y);
}
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7