497.Shape Factory-形状工厂(容易题)

形状工厂

  1. 题目

    工厂模式是一种常见的设计模式。实现一个形状工厂 ShapeFactory 来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。

  2. 样例

    这里写图片描述

  3. 题解

唯一需要注意的就是反斜杠\的转义问题,用“\\”表示。

/**
 * Your object will be instantiated and called as such:
 * ShapeFactory sf = new ShapeFactory();
 * Shape shape = sf.getShape(shapeType);
 * shape.draw();
 */
interface Shape {
    void draw();
}

class Rectangle implements Shape {
    public void draw()
    {
        System.out.println(" ----");
        System.out.println("|    |");
        System.out.println(" ----");
    }
}

class Square implements Shape {
    public void draw()
    {
        System.out.println(" ----");
        System.out.println("|    |");
        System.out.println("|    |");
        System.out.println(" ----");
    }
}

class Triangle implements Shape {
    public void draw()
    {
        System.out.println("  /\\");
        System.out.println(" /  \\");
        System.out.println("/____\\");
    }
}

public class ShapeFactory {
    /**
     * @param shapeType a string
     * @return Get object of type Shape
     */
    public Shape getShape(String shapeType) {
        Shape shape = null;
        if (shapeType.equals("Rectangle"))
        {
            shape = new Rectangle();
        }
        else if (shapeType.equals("Square"))
        {
            shape = new Square();
        }
        else if (shapeType.equals("Triangle"))
        {
            shape = new Triangle();
        }
        return shape;
    }
}

Last Update 2016.9.18

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为您解答。简单工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在简单工厂模式中,我们创建一个工厂类,该类负责创建其他类的对象,而不是在代码中直接实例化它们。下面是一个可以创建不同几何形状的简单工厂类的示例代码: ```python class ShapeFactory: def create_shape(self, shape_type): if shape_type == 'circle': return Circle() elif shape_type == 'rectangle': return Rectangle() elif shape_type == 'triangle': return Triangle() else: raise ValueError('Invalid shape type') ``` 在上面的代码中,我们定义了一个 ShapeFactory 类,它有一个 create_shape 方法,该方法接受一个字符串参数 shape_type,根据这个参数来创建不同的几何形状对象。如果传入的 shape_type 不是 'circle'、'rectangle' 或 'triangle' 中的任何一个,那么就会抛出一个 ValueError 异常。 下面是三个几何形状类的示例代码: ```python class Circle: def draw(self): print('Drawing a circle') class Rectangle: def draw(self): print('Drawing a rectangle') class Triangle: def draw(self): print('Drawing a triangle') ``` 这些类都有一个 draw 方法,用于绘制相应的几何形状。 现在我们可以使用 ShapeFactory 类来创建不同的几何形状对象了: ```python factory = ShapeFactory() circle = factory.create_shape('circle') circle.draw() # 输出:Drawing a circle rectangle = factory.create_shape('rectangle') rectangle.draw() # 输出:Drawing a rectangle triangle = factory.create_shape('triangle') triangle.draw() # 输出:Drawing a triangle ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值