Abstract factory pattern looks similar to factory method pattern, but factory method pattern builds objects that inherit the same abstract class, and the objects created by abstract factory pattern do not inherit from the same base class. Therefore, we can't use the reflection like factory method pattern to create objects
Abstract factory pattern can be divided into four categories: abstract factory, concrete factory, abstract product and concrete product.
Different from the factory method pattern, there is only one abstract product class and concrete factory class in the factory method pattern, while there may be many abstract product classes and concrete factory classes in the abstract factory pattern, which is equivalent to that each product has different components
Abstract product class
public abstract class AbstractPartA {
public abstract void statement();
}
public abstract class AbstractPartB {
public abstract void statement();
}
Specific products
public class PartA1 extends AbstractPartA {
@Override
public void statement() {
System.out.println("PartA1");
}
}
public class PartA2 extends AbstractPartA {
@Override
public void statement() {
System.out.println("PartA2");
}
}
public class PartB1 extends AbstractPartB {
@Override
public void statement() {
System.out.println("PartB1");
}
}
public class PartB2 extends AbstractPartB {
@Override
public void statement() {
System.out.println("PartB2");
}
}
The specific product category here is similar to that of a product. There are many grades of parts. A and B are two different parts, while A1 and A2 represent two different grades. Let's assume that A1 here is a little better than A2, which is more expensive
Abstract factory class
public abstract class AbstractFactory {
public abstract AbstractPartA createPartA();
public abstract AbstractPartB createPartB();
}
Specific factory
The specific factory class is similar to the combination of the above specific products
public class ProductFactoryOne extends AbstractFactory {
@Override
public AbstractPartA createPartA() {
return new PartA1();
}
@Override
public AbstractPartB createPartB() {
return new PartB2();
}
}
public class ProductFactoryTwo extends AbstractFactory {
@Override
public AbstractPartA createPartA() {
return new PartA2();
}
@Override
public AbstractPartB createPartB() {
return new PartB2();
}
}