使用简单工厂模式设计一个可以创建不同几何图形(Shape),如Circle,Rectangle,Triangle等绘图工具类,每个几何图形均具有绘制Draw()和擦除Erase()两个方法;要求在绘制不支持的几何图形时,抛出一个UnsuppShapeException异常,绘制类图并使用Java语言实现。
/** * Description: 抽象产品角色 */
public abstract class Shape {
public abstract void draw();
public abstract void erase();
}
/** * Description: 具体产品角色 */
public class Round extends Shape {
@Override public void draw() {
System.out.println("绘制圆形");
}
@Override public void erase() {
System.out.println("擦除圆形");
}
}
public class Square extends Shape {
@Override public void draw() {
System.out.println("绘制方形");
}
@Override public void erase() {
System.out.println("擦除方形");
}
}
public class Triangle extends Shape {
@Override public void draw() {
System.out.println("绘制三角形");
}
@Override public void erase() {
System.out.println("擦除三角形");
}
}
/** * Description: 工厂角色 */
public class ShapeFactory { // 声明创建形状的静态工厂方法
public static Shape createShape(String type) throws UnSupportedShapeException {
Shape shape;
if ("圆形".equals(type)) {
shape = new Round();
}
else if ("方形".equals(type)) {
shape = new Square();
}
else if ("三角形".equals(type)) {
shape = new Triangle();
}
else {
throw new UnSupportedShapeException("UnSupportedShapeException");
}
return shape;
}
}
/** * Description: 自定义异常 */
public class UnSupportedShapeException extends Exception {
public UnSupportedShapeException(String message) {
super(message);
}
}
/** * Description: 客户端 */
public class DrawingTool {
public static void main(String[] args) {
Shape s1, s2, s3, s4; try {
s1 = ShapeFactory.createShape("圆形");
s2 = ShapeFactory.createShape("方形");
s3 = ShapeFactory.createShape("三角形");
s1.draw(); s1.erase();
s2.draw(); s2.erase();
s3.draw(); s3.erase();
// s4.draw(); // s4.erase();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}