假设我有一个计算形状面积的 Shape 接口。我添加了 2 个实现矩形和正方形。我看到的挑战是两种实现都有自己的多参数构造函数。如何使用工厂模式初始化它们。我想用java来解决这个问题。
public class Rectangle implements Shape {
int length;
int breadth;
public Rectangle(List<String> parameters) {
this.length = Integer.parseInt(parameters.get(0));
this.breadth = Integer.parseInt(parameters.get(1));
}
@Override
public int area() {
return length * breadth;
}
}
public class Square implements Shape {
int edge;
public Square(List<String> parameters) {
this.edge = Integer.parseInt(parameters.get(0));
}
@Override
public int area() {
return edge * edge;
}
}
public interface Shape {
int area();
}
public interface ShapeFactory {
public Shape make(String shapeType);
public List<String> getParameters(String shapeType);
}
public class ShapeFactoryImpl implements ShapeFactory {
Map<String, List<String>> shapeInitMap = new HashMap<>();
public void init(){
shapeInitMap.put("Circle", Arrays.asList(new String[]{"4"}));
shapeInitMap.put("Rectangle", Arrays.asList(new String[]{"2","3"}));
}
@Override
public Shape make(String shapeType) {
switch (shapeType) {
case "Circle":
return new Square(getParameters(shapeType));
case "Square":
return new Rectangle(getParameters(shapeType));
default:
break;
}
return null;
}
@Override
public List<String> getParameters(String shapeType) {
return shapeInitMap.get(shapeType);
}
}
潇潇雨雨
相关分类