java - 如何在使用抽象工厂模式时更改可独立部署的类的值?
问题描述
我目前正在尝试学习一些设计模式,并为可独立部署的工厂模式做了一个示例。
我现在的问题是,如果我想更改 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);
}
}
解决方案
推荐阅读
- css - 使用百分比时 Chrome 中的变换位置不正确
- rocket.chat - 升级后迁移期间的 Rocketchat 错误
- ios - 我可以用 i386 + x86_64 架构构建 IPA 吗?
- node.js - 运行 ng test 命令时出现 Karma“非法访问”错误
- android - 构建 PhoneGap 应用程序时出错
- angular - 将组件用作自定义元素和角度组件
- python - Python ValueError:操作数无法与形状一起广播(180,180)(100,100)
- amazon-web-services - AWS 凭证已刷新但仍过期
- css - 无法在 Div 中居中图像
- c++ - 在 char 之后插入空格函数在代码之外工作但在 C++ 中返回错误