时间限制:1.000S 空间限制:256MB
题目描述
公司正在开发一个图形设计软件,其中有一个常用的图形元素是矩形。设计师在工作时可能需要频繁地创建相似的矩形,而这些矩形的基本属性(如颜色、宽度、高度)相同,但具体的位置可能不同。
为了提高设计师的工作效率,请你使用原型模式设计一个矩形对象的原型。该原型可以根据用户的需求进行克隆,生成新的矩形对象。
输入描述
第一行输入一个整数 N(1 ≤ N ≤ 100),表示需要创建的矩形数量。
接下来的 N 行,每行输入一个字符串,表示矩形的属性信息,分别为颜色,长度,宽度,比如 "Red 10 5"。
输出描述
对于每个矩形,输出一行字符串表示矩形的详细信息,如 "Color: Red, Width: 10,Height: 5"。
输入示例
3
Red 10 5
Blue 15 8
Green 12 6
输出示例
Color: Red, Width: 10, Height: 5
Color: Blue, Width: 15, Height: 8
Color: Green, Width: 12, Height: 6
提示信息
使用原型模式中的克隆方法实现矩形对象的创建。
import java.util.Scanner;
// 抽象原型类
abstract class Prototype implements Cloneable {
public abstract Prototype clone();
public abstract String getDetails();
// 公共的 clone 方法
public Prototype clonePrototype() {
try {
// 返回克隆类
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
// 出现异常打印
e.printStackTrace();
return null;
}
}
}
// 具体矩形原型类
class RectanglePrototype extends Prototype {
private String color;
private int width;
private int height;
// 构造方法
public RectanglePrototype(String color, int width, int height) {
this.color = color;
this.width = width;
this.height = height;
}
// 克隆方法
@Override
public Prototype clone() {
return clonePrototype();
}
// 获取矩形的详细信息
@Override
public String getDetails() {
return "Color: " + color + ", Width: " + width + ", Height: " + height;
}
}
// 客户端程序
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 读取需要创建的矩形数量
int n = sc.nextInt();
// 读取每个矩形的属性信息并创建矩形对象
for (int i = 0; i < n; i++) {
String color = sc.next();
int width = sc.nextInt();
int height = sc.nextInt();
// 创建原型对象
Prototype originalRectangle = new RectanglePrototype(color, width, height);
// 克隆对象并输出详细信息
Prototype clonedRectangle = originalRectangle.clone();
//输出该对象的信息
System.out.println(clonedRectangle.getDetails());
}
}
}
本文含有隐藏内容,请 开通VIP 后查看