Here this example demonstrates how to implement AbstractFactory Pattern in Java.
Source Code
package com.beginner.examples;
//product 1
abstract class Product1 {
public abstract void product1();
}
//product 2
abstract class Product2 {
public abstract void product2();
}
//detail product
class MilkTea extends Product1 {
@Override
public void product1() {
System.out.println("a milk tea");
}
}
class Juice extends Product1 {
@Override
public void product1() {
System.out.println("a juice");
}
}
class Bread extends Product2 {
@Override
public void product2() {
System.out.println("a bread");
}
}
class Sausage extends Product2 {
@Override
public void product2() {
System.out.println("a sausage");
}
}
//abstract factory
abstract class Factory {
abstract Product1 createProduct1();
abstract Product2 createProduct2();
}
//detail factory
class Factory1 extends Factory {
@Override
public Product1 createProduct1() {
return new MilkTea();
}
@Override
public Product2 createProduct2() {
return new Bread();
}
}
class Factory2 extends Factory {
@Override
public Product1 createProduct1() {
return new Juice();
}
@Override
public Product2 createProduct2() {
return new Sausage();
}
}
public class AbstractFactoryExample {
public static void main(String[] args) {
Factory factory1 = new Factory1();
Factory factory2 = new Factory2();
factory1.createProduct1().product1();
factory2.createProduct1().product1();
factory1.createProduct2().product2();
factory2.createProduct2().product2();
}
}
Output:
a milk tea
a juice
a bread
a sausage