See the author’s blog for a detailed explanation of the abstract factory pattern

Part 2 creative design patterns chapter 3 abstract factory patterns (A: C++ implementation)

This article is a Java implementation of the Abstract Factory pattern.

Step 1: Create an abstract product

Create product A.

package com;

public interface ProductA {
	public void show(a);
}
Copy the code

Create product B.

package com;

public interface ProductB {
	public void show(a);
}
Copy the code

Step 2: Implement specific products

Implement product A.

package com;

public class ProductA1 implements ProductA{
	public void show(a) 
	{
		System.out.println("I'm ProductA1"); }}Copy the code
package com;

public class ProductA2 implements ProductA{
	public void show(a) 
	{
		System.out.println("I'm ProductA2"); }}Copy the code

Implement product B.

package com;

public class ProductB1 implements ProductB{
	public void show(a) 
	{
		System.out.println("I'm ProductB1"); }}Copy the code
package com;

public class ProductB2 implements ProductB{
	public void show(a) 
	{
		System.out.println("I'm ProductB2"); }}Copy the code

Step 3: Create an image factory

package com;

public interface Factory {
	public ProductA CreateProductA(a);
	public ProductB CreateProductB(a);
}
Copy the code

Step 4: Implement the specific factory

Implement Factory 1.

package com;

public class Factory1 implements Factory{

	public ProductA CreateProductA(a)
	{
		return new ProductA1();
	}
	public ProductB CreateProductB(a)
	{
		return newProductB1(); }}Copy the code

Implement Factory 1.

package com;

public class Factory2 implements Factory{
	public ProductA CreateProductA(a)
	{
		return new ProductA2();
	}
	public ProductB CreateProductB(a)
	{
		return newProductB2(); }}Copy the code

Step 5: Test

package com;

public class Main {

	public static void main(String[] args) {
		
		Factory factoryObj1 = new Factory1();
		ProductA productObjA1 = factoryObj1.CreateProductA();
		ProductB productObjB1 = factoryObj1.CreateProductB();
		productObjA1.show();
		productObjB1.show();
		
		Factory factoryObj2 = newFactory2(); ProductA productObjA2 = factoryObj2.CreateProductA(); ProductB productObjB2 = factoryObj2.CreateProductB(); productObjA2.show(); productObjB2.show(); }}Copy the code

Well, the author of the abstract factory pattern of Java implementation of this end, thank you for your support.