一、java版


抽象产品A ->  ProductA.java :


public interface ProductA {
    public void fun();
}


具体产品A1 -> ProductA1.java :

public class ProductA1 implements ProductA{
    @Override
    public void fun() {
        System.out.println("ProudctA1 -> fun()");
    }
                                                                                                                                 
}


具体产品A2  -> ProductA2.java :

public class ProductA2 implements ProductA {
    @Override
    public void fun() {
        System.out.println("ProductA2 -> fun()");
    }
}


抽象产品B ->  ProductB.java :


public interface ProductB {
    public void fun();
}


具体产品B1 -> ProductB1.java :


public class ProductB1 implements ProductB {
    @Override
    public void fun() {
        System.out.println("ProductB1 -> fun()");
    }
}


具体产品B2 -> ProductB2.java :


public class ProductB2 implements ProductB {
    @Override
    public void fun() {
        System.out.println("ProductB2 -> fun()");
    }
}


抽象工厂 -> Factory.java :


public interface Factory {
    public ProductA getProductA();
    public ProductB getProductB();
}


具体工厂1 -> Factory1.java :


public class Factory1 implements Factory {
    @Override
    public ProductA getProductA() {
        return new ProductA1();
    }
    @Override
    public ProductB getProductB() {
        return new ProductB1();
    }
}


具体工厂2 -> Factory2.java :


public class Factory2 implements Factory {
    @Override
    public ProductA getProductA() {
        return new ProductA2();
    }
    @Override
    public ProductB getProductB() {
        return new ProductB2();
    }
}


测试 -> Test.java :


public class Test {
                 
    public static void main(String[] args) {
                     
        Factory factory;
                     
        factory = new Factory1();
        factory.getProductA().fun();
        factory.getProductB().fun();
                     
        factory = new Factory2();
        factory.getProductA().fun();
        factory.getProductB().fun();
                     
    }
}


测试结果:


ProudctA1 -> fun()

ProductB1 -> fun()

ProductA2 -> fun()

ProductB2 -> fun()