简单工厂模式实例

问题描述

使用简单工厂模式设计一个可以创建不同几何形状(Shape),如圆形(Circle)、矩形
(Rectangle)和三角形(Triangle)等的绘图工具类,每个几何图形均具有绘制Draw()和擦除
Erase()两个方法,要求在绘制不支持的几何图形时,抛出一个UnsupportedShapeException
异常。绘制类图并编程模拟实现。

结构图

在这里插入图片描述

编程实现

接口

public interface Shape {
    void draw();
    void erase();
}

实现类

public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("draw circle");
    }

    @Override
    public void erase() {

        System.out.println("erase circle");
    }
}
public class Rectangle implements Shape{
    @Override
    public void draw() {
        System.out.println("draw Rectangle");
    }

    @Override
    public void erase() {

        System.out.println("erase Rectangle");
    }
}
public class Triangle implements Shape{
    @Override
    public void draw() {
        System.out.println("draw triangle");
    }

    @Override
    public void erase() {

        System.out.println("erase triangle");
    }
}

自定义UnsupportedShapeException异常类

public class UnsupportedShapeException extends Exception{
    static final long serialVersionUID = -3387516993124225558L;

    public UnsupportedShapeException(){
    }

    public UnsupportedShapeException(String message){
        System.out.println(message);
    }
}

工厂类

public class ShapeFactory {
    public static Shape createShape(String name) throws Exception{
        Shape newShape=null;
        if("circle".equalsIgnoreCase(name)){
            newShape=new Circle();
        }else if ("rectangle".equalsIgnoreCase(name)){
            newShape=new Rectangle();
        }else if ("triangle".equalsIgnoreCase(name)){
            newShape=new Triangle();
        }else {
            throw new UnsupportedShapeException("需要创建的图形不存在");
        }

        return newShape;
    }

客户端

public class Client {
    public static void main(String[] args) {
        try {
            Shape shape=ShapeFactory.createShape("rectangle");
            shape.draw();
            shape.erase();
            shape=ShapeFactory.createShape("ellipse");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值