Create object abstract factory pattern under the same category

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();
    }
}
Of course, I don't know these two combinations. There should be four. I won't list them one by one

Posted by barry_p on Fri, 01 May 2020 20:06:52 -0700