StrategyAdvertisementアルゴリズムをまるごと入れ替える
複数のアルゴリズムを作成し、状況により切り替えたい場合などに有効。
例 開発環境ではJDBC接続、運用環境ではJNDI接続をする。 複数のアルゴリズムを実装しておき、負荷テスト・速度テストの際に入れ替えて実験する。 など。 サンプル
指定したプロパティの値により、面積の計算方法を変更する。
指定したクラスが三角形の場合:幅×高さ÷2 指定したクラスが四角形の場合:幅×高さ ■figure.java /** * 全ての図形のスーパークラス * * @author * @version 1.0 */ abstract public class Figure { /** 図形の高さ */ private float height; /** 図形の幅 */ private float width; /** * 図形の高さを設定する * @param height 図形の高さ */ public void setHeight(float height){ this.height = height; } /** * 図形の幅を設定する * @param width 図形の幅 */ public void setWidth(float width){ this.width = width; } /** * 図形の高さを返す * @return 図形の高さ */ public float getHeight(){ return this.height; } /** * 図形の幅を返す * @return 図形の幅 */ public float getWidth(){ return this.width; } /** * 図形の面積を返す * @return 図形の面積 */ abstract public float getArea(); } ■Square.java /** * 四角形を表すクラス * * @author * @version 1.0 */ public class Square extends Figure{ public Square() {} /** * この図形の面積を返す * @return 図形の面積 */ public float getArea(){ return this.getHeight() * this.getWidth(); } } ■Triangle.java /** * 三角形を表すクラス * * @author * @version 1.0 */ public class Triangle extends Figure{ public Triangle() {} /** * この図形の面積を返す * @return 図形の面積 */ public float getArea(){ return this.getHeight() * this.getWidth() / 2.0f; } } ■StrategyTest.java
import java.util.ResourceBundle;
public class StrategyTest {
public static void main(String[] args){
Figure figure = null;
// リソースファイルから生成するクラス名を取得する。
ResourceBundle resource = ResourceBundle.getBundle("algorithm");
String type = resource.getString("figure");
System.out.println(type);
// インスタンスを生成する。
try{
Class concreteClass = Class.forName(type);
figure = (Figure)concreteClass.newInstance();
}catch(ClassNotFoundException cne){
cne.printStackTrace();
System.exit(1);
}catch(IllegalAccessException iae){
iae.printStackTrace();
System.exit(1);
}catch(InstantiationException ie){
ie.printStackTrace();
System.exit(1);
}
// メソッド呼び出し
figure.setWidth(100.0f);
figure.setHeight(100.0f);
System.out.println(figure.getArea());
}
}
■algorithm.properties
figure=Triangle
#figure=Square
クラス図
Advertisement |
ショートカット・634・634ブログ ・このカテゴリのトップページに戻る ・Incubator(Pukiwiki) ・634ラボ UIコレクションギャラリー ZO-3ジェネレーター サイト検索Y!ログールビリヤード |