抽象工厂方法模式

抽象工厂模式是工厂模式的一个升级版,它提供了一个通用的接口来创建一组相关的对象,而不是单个对象。该模式适用于需要动态生成一组相关对象的场景,如GUI工具包中的按钮、文本框等。

在Java中,抽象工厂模式(Abstract Factory Pattern)是一种创建型设计模式,它属于工厂方法模式的进一步抽象。抽象工厂模式提供了一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类.

下面通过一个示例来展示如何实现抽象工厂模式

1、定义产品接口,所有的产品类都将实现这个接口。

public interface Shape {
    void draw();
}

2、实现产品接口,实现这个接口的多个类。

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

3、定义颜色接口及其实现类。

public interface Color {
    void fill();
}

public class Red implements Color {
    @Override
    public void fill() {
        System.out.println("Inside Red::fill() method.");
    }
}

public class Green implements Color {
    @Override
    public void fill() {
        System.out.println("Inside Green::fill() method.");
    }
}

4、定义一个抽象工厂接口,用于创建不同类型的图形和颜色。

public interface AbstractFactory {
    Color getColor(String color);
    Shape getShape(String shape) throws Exception;
}

5、实现抽象工厂接口以创建具体的工厂类

public class ShapeFactory implements AbstractFactory {
    @Override
    public Color getColor(String color) {
        return null; // 这里可以返回颜色的实例,但在这个例子中我们只关注形状。返回null或特定默认颜色实例。
    }
    @Override
    public Shape getShape(String shapeType) throws Exception {
        if (shapeType == null) {
            return null; // 或者抛出异常,取决于具体实现需求。
        } else if (shapeType.equalsIgnoreCase("Square")) {
            return new Square();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        } 
        throw new Exception("Shape does not exist"); // 或者返回null,具体取决于你的设计需求。
    }
}

6、使用抽象工厂来获取产品对象并测试它们的功能

public class AbstractFactoryPatternDemo {
    public static void main(String[] args) throws Exception {
        AbstractFactory shapeFactory = new ShapeFactory(); // 可以根据需要切换到其他工厂类。例如颜色工厂等。 
        Shape shape1 = shapeFactory.getShape("Square"); // 获取正方形对象并调用其draw方法。 
        shape1.draw(); // 输出:Inside Square::draw() method. 
        Shape shape2 = shapeFactory.getShape("RECTANGLE"); // 获取矩形对象并调用其draw方法。 
        shape2.draw(); // 输出:Inside Rectangle::draw() method. 
    } 
} 

这个示例展示了如何使用抽象工厂模式来创建和组合不同类型的产品(形状和颜色)。你可以根据需要扩展此模式,比如添加颜色工厂等其他类型的工厂。这样可以根据不同的配置或需求创建不同类型的对象族。