题目:
1. 使用简单工厂模式设计一个可以创建不同几何形状(Shape)的绘图工具类,如可创建圆形(Circle)、矩形(Rectangle)、和三角形(Triangle)对象,每个几何图形均具有绘制和擦除两个方法,要求在绘制不支持的几何图形时,抛出一个异常(UnsupportedShapeException),或实现一个简单计算器,绘制类图并编程实现。
类图
package cn.factory1;
public class Circle implements Shape {
public void init() {
System.out.println("创建圆形。。。");
}
}package cn.factory1;
public class Rectangle implements Shape {
public void init() {
System.out.println("创建长方形。。。");
}
}package cn.factory1;
public interface Shape {
public void init();
}package cn.factory1;
public class ShapeFactory {
public static Shape initShape(String name) throws Exception {
if(name.equalsIgnoreCase("Circle")){
System.out.println("图形工厂生产圆形!");
return new Circle();
}
else if(name.equalsIgnoreCase("Triangle")) {
System.out.println("图形工厂生产三角形!");
return new Triangle();
}
else if(name.equalsIgnoreCase("Rectangle")) {
System.out.println("图形工厂生产长方形!");
return new Rectangle();
}
else {
throw new Exception("对不起,暂不能生产该种图形!");
}
}
public static void deleteShape(String name) throws Exception {
if(name.equalsIgnoreCase("Circle")){
System.out.println("已销毁圆形!");
}
else if(name.equalsIgnoreCase("Triangle")) {
System.out.println("已销毁三角形!");
}
else if(name.equalsIgnoreCase("Rectangle")) {
System.out.println("已销毁长方形!");
}
else {
throw new Exception("对不起,图形工厂中没有该种图形!");
}
}
}
package cn.factory1;
public class SimpleFac {
public static void main(String[] args) {
try {
Shape shape;
shape = ShapeFactory.initShape("Circle");
shape.init();
//shape = ShapeFactory.initShape("Triangle");
//shape.init();
//shape = ShapeFactory.initShape("Rectangle");
//shape.init();
//shape = ShapeFactory.initShape("app");
//shape.init();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
package cn.factory1;
public class Triangle implements Shape {
public void init() {
System.out.println("创建三角形。。。");
}
}运行效果图
注意:这个程序是在SimpleFac类中运行
本文介绍了一个使用简单工厂模式设计的绘图工具类,能够创建不同的几何形状,包括圆形、矩形和三角形,并实现了绘制和擦除的功能。当尝试创建不支持的图形时会抛出异常。
1261

被折叠的 条评论
为什么被折叠?



