Abstract Factory パターン
1月 1, 2003 · Posted in GoFデザインパターン · Comment
抽象的な工場を作る
製品を作成する工場と、その工場が作成する製品を共に抽象化することにより、クライアントが目的にあった工場を選択できるようにする。
特徴
工場を抽象化する。
クライアントが指定する工場により、作成できる製品が異なる。
最大限に抽象化を行う
工場と製品を共に抽象化することにより、組み合わせを柔軟に指定できる。
どんなときに有効か。
部品の組み合わせパターンが多いときに有効。
組み合わせて使うサブクラス群をまとめて切り替えるときに有効。
サンプルコード
※上手くまとまっていないので、後日修正予定。
Factory クラス(抽象的な工場)
abstract class Factory{
public abstract Header getHeader();
public abstract Body getBody(String document);
public abstract Footer getFooter();
}
Item クラス(抽象的な部品)
abstract class Item{
public abstract void print();
}
Body クラス(抽象的な部品)
abstract class Body extends Item{
}
Header クラス(抽象的な部品)
abstract public class Header extends Item{
}
Footer クラス(抽象的な部品)
abstract public class Footer extends Item{
}
– ここまでが抽象的なクラス
NormalFactory クラス(具体的なクラス)
class NormalFactory extends Factory{
public Header getHeader(){
return new NormalHeader();
}
public Body getBody(String document){
return new NormalBody(document);
}
public Footer getFooter(){
return new NormalFooter();
}
}
NormalHeader クラス(具体的なクラス)
public class NormalHeader extends Header{
public void print(){
System.out.println("--top--");
}
}
NormalBody クラス(具体的なクラス)
public class NormalBody extends Body{
private String document;
public NormalBody(String document){
this.document = document;
}
public void print(){
System.out.println(document);
}
}
NormalFooter クラス(具体的なクラス)
public class HtmlFooter extends Footer{
public void print(){
System.out.println("
