首页 > 解决方案 > 如何在使用抽象工厂模式时更改可独立部署的类的值?

问题描述

我目前正在尝试学习一些设计模式,并为可独立部署的工厂模式做了一个示例。

我现在的问题是,如果我想更改 Rectangle 的任何值,我将创建对 Rectangle 类的依赖。我可以将这些方法放入 Shape 接口,但如果我添加的下一个形状是圆形,那将没有多大意义。

如何在不依赖 Rectangle 类的情况下更改值?

形状.java

public interface Shape {}

ShapeFactory.java

public interface ShapeFactory {
    Shape create(String shape);
}

矩形.java

public class Rectangle implements Shape {
    private int top, left, bottom, right;

    public Rectangle(int top, int left, int bottom, int right) {
        setTopLeft(top, left);
        setBottomRight(bottom, right);
    }

    public void setTopLeft(int top, int left) {
        this.top = top;
        this.left = left;
    }

    public void setBottomRight(int bottom, int right) {
        this.bottom = bottom;
        this.right = right;
    }
}

ShapeFactoryImpl.java

public class ShapeFactoryImpl implements ShapeFactory {
    public Shape create(String shape) throws RuntimeException {
        if (shape.equals("rectangle")) 
            return new Rectangle(0, 0, 1, 1);

        throw new IllegalArgumentException();
    }
}

应用程序.java

public class App {
    ShapeFactory shapeFactory;

    public static void main(String[] args) {
        App app = new App();

        app.setShapeFactory(new ShapeFactoryImpl());
        Shape rectangle = app.create("rectangle");

        // don't want this
        ((Rectangle) rectangle).setTopLeft(1,2);
        ((Rectangle) rectangle).setBottomRight(2,3);
    }

    private void setShapeFactory(ShapeFactoryImpl shapeFactory) {
        this.shapeFactory = shapeFactory;
    }

    private Shape create(String shape) {
        return shapeFactory.create(shape);
    }
}

标签: javaabstract-factory

解决方案


推荐阅读