我查看了使用抽象工厂和工厂方法的示例。但是我怎样才能正确地将两者结合起来,所以抽象工厂会选择需要哪个具体工厂,然后工厂方法会选择在给定工厂中创建什么。我试图让自己成为一个使用这些模式的程序,但陷入了死胡同。无法弄清楚如何正确组合这两种模式以使我的程序正常工作。我的程序非常简单。它只会创建家具 - 桌子或椅子,具体取决于所选的混凝土工厂。
如果选择了 Table Factory,它将创建圆桌或方桌(也是书写类型,圆形或方形)。如果选择该工厂,那么对于椅子工厂也是如此。
所以我的代码看起来像这样(某些部分可能不正确,因为这就是我问这个问题的原因):
package pack1;
//abstract product
public abstract class Table {
protected final String name;
public Table(String name) {
this.name = name;
}
}
package pack1;
//concrete product
public class SquareTable extends Table {
public SquareTable(String name) {
super(name);
}
}
package pack1;
//concrete product
public class RoundTable extends Table {
public RoundTable(String name) {
super(name);
}
}
package pack1;
//abstract product
public abstract class Chair {
protected final String name;
public Chair(String name) {
this.name = name;
}
}
package pack1;
//concrete product
public class WoodenChair extends Chair {
public WoodenChair(String name) {
super(name);
}
}
package pack1;
//concrete product
public class MetalChair extends Chair {
public MetalChair(String name) {
super(name);
}
}
package pack1;
//Abstract Factory
public interface AbstractFurnitureFactory {
public Table createTable(String type, String name);
//not finished. How to use different create methods for different factories,
//so it wouldn't require to use this method in concrete factories or
//do I need 2 concrete factories for this to work?..
}
package pack1;
//concrete factory
public class TableFactory implements AbstractFurnitureFactory {
public Table createTable(String type, String name){
if(type.equals("square"))
{
SquareTable sq_table=new SquareTable(name);
return sq_table;
}
else
{
RoundTable rn_table=new RoundTable(name);
return rn_table;
}
}
}
package pack1;
//concrete factory
public class ChairFactory {
public Chair createChair(String type, String name){
if(type.equals("wood"))
{
WoodenChair wd_chair=new WoodenChair(name);
return wd_chair;
}
else
{
MetalChair mt_chair=new MetalChair(name);
return mt_chair;
}
}
}
package pack1;
//client
public class FurnitureBuilder {
public void buildTable(AbstractFurnitureFactory tf)
{
//Table table = tf.createTable();
//table.name = "New table";
//not Finished. Java won't let me set arguments in createTable
//method for example. It gives error - 'The method
//createTable(String, String) in the type
//AbstractFurnitureFactory is not applicable for the arguments ()'
}
}
package pack1;
public class Main {
public static void main(String[] args)
{
//FurnitureBuilder builder = new FurnitureBuilder();
//AbstractFurnitureFactory TableFactory = null;
//Not finished as some parts are missing.
}
}
因此,如果有人可以查明和/或修复我做错了什么,我将非常感激。