Abstract Factory と Factory デザイン パターンの違いは、AbstractFactory パターンはコンポジションを使用してオブジェクトを作成する責任を別のクラスに委任するのに対し、Factory デザイン パターンは継承を使用し、派生クラスまたはサブクラスに依存してオブジェクトを作成することです。
以下は、抽象ファクトリの典型的な例です ( http://www.oodesign.com/abstract-factory-pattern.html ) 抽象ファクトリがオブジェクト構成を使用している場所を説明してもらえますか?
abstract class AbstractProductA{
public abstract void operationA1();
public abstract void operationA2();
}
class ProductA1 extends AbstractProductA{
ProductA1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}
class ProductA2 extends AbstractProductA{
ProductA2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}
abstract class AbstractProductB{
//public abstract void operationB1();
//public abstract void operationB2();
}
class ProductB1 extends AbstractProductB{
ProductB1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}
class ProductB2 extends AbstractProductB{
ProductB2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}
abstract class AbstractFactory{
abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}
class ConcreteFactory1 extends AbstractFactory{
AbstractProductA createProductA(){
return new ProductA1("ProductA1");
}
AbstractProductB createProductB(){
return new ProductB1("ProductB1");
}
}
class ConcreteFactory2 extends AbstractFactory{
AbstractProductA createProductA(){
return new ProductA2("ProductA2");
}
AbstractProductB createProductB(){
return new ProductB2("ProductB2");
}
}
ConcreteFactory1
私はサブクラスを理解ConcreteFactory1
し、オブジェクトをクライアントに返しています。通常、複数の製品を持つ Factory クラスとして機能します。
クライアントコードがどこにあるのか
AbstractFactory factory = new ConcreteFactory2();
AbstractProductA prodA = factory.createProductA();
抽象ファクトリのどこでオブジェクトの構成/委任が行われるのか説明してもらえますか?