問題一覧に戻る
上級高度な機能
問題115: ファクトリーパターン

ファクトリーパターンを使用してオブジェクト生成を抽象化します。インスタンス化ロジックをカプセル化し、実行時パラメータに基づく柔軟なオブジェクト生成を提供する方法を学びます。

interface Shape {
void draw();
}

class Circle implements Shape {
public void draw() { System.out.println("Circle"); }
}

class Square implements Shape {
public void draw() { System.out.println("Square"); }
}

// ファクトリークラス
class ShapeFactory {
public Shape createShape(String type) {
if (type.equals("circle")) {
return new ();
} else if (type.equals("square")) {
return new ();
}
return ;
}
}