当前位置: 面试刷题>> 形状工厂 (经典算法题500道)


题目描述补充

题目:形状工厂(Shape Factory)

在一个面向对象编程(OOP)的语境下,我们需要设计一个“形状工厂”来动态地创建不同类型的形状对象。这些形状对象(如圆形、矩形、三角形等)都应该继承自一个共同的基类或接口,以确保它们具有一些共同的方法,如计算面积或周长。形状工厂的任务是根据传入的参数(如形状类型和必要的尺寸信息)来创建并返回相应类型的形状对象实例。

示例要求

  • 定义一个Shape接口,包含calculateArea()calculatePerimeter()方法。
  • 创建CircleRectangleTriangle类,这些类实现Shape接口。
  • 实现一个ShapeFactory类,该类有一个静态方法getShape,根据传入的形状类型字符串和必要的尺寸信息来创建并返回相应的形状对象。

示例代码

PHP 示例

interface Shape {
    public function calculateArea();
    public function calculatePerimeter();
}

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }

    public function calculatePerimeter() {
        return 2 * pi() * $this->radius;
    }
}

// Rectangle 和 Triangle 类实现类似,这里省略

class ShapeFactory {
    public static function getShape($shapeType, $width, $height = 0, $radius = 0) {
        switch ($shapeType) {
            case 'circle':
                return new Circle($radius);
            case 'rectangle':
                return new Rectangle($width, $height);
            case 'triangle':
                // 假设三角形以底和高定义
                return new Triangle($width, $height);
            default:
                throw new Exception('Invalid shape type');
        }
    }
}

// 示例用法
$circle = ShapeFactory::getShape('circle', 0, 0, 5);
echo "Circle Area: " . $circle->calculateArea() . PHP_EOL;

Python 示例

from abc import ABC, abstractmethod
from math import pi

class Shape(ABC):
    @abstractmethod
    def calculate_area(self):
        pass

    @abstractmethod
    def calculate_perimeter(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return pi * (self.radius ** 2)

    def calculate_perimeter(self):
        return 2 * pi * self.radius

# Rectangle 和 Triangle 类实现类似,这里省略

class ShapeFactory:
    @staticmethod
    def get_shape(shape_type, **kwargs):
        if shape_type == 'circle':
            return Circle(kwargs['radius'])
        elif shape_type == 'rectangle':
            return Rectangle(kwargs['width'], kwargs['height'])
        elif shape_type == 'triangle':
            return Triangle(kwargs['width'], kwargs['height'])
        else:
            raise ValueError("Invalid shape type")

# 示例用法
circle = ShapeFactory.get_shape('circle', radius=5)
print(f"Circle Area: {circle.calculate_area()}")

JavaScript 示例

class Shape {
    calculateArea() {
        throw new Error('This is an abstract method.');
    }

    calculatePerimeter() {
        throw new Error('This is an abstract method.');
    }
}

class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }

    calculateArea() {
        return Math.PI * this.radius ** 2;
    }

    calculatePerimeter() {
        return 2 * Math.PI * this.radius;
    }
}

// Rectangle 和 Triangle 类实现类似,这里省略

class ShapeFactory {
    static getShape(shapeType, width, height = 0, radius = 0) {
        switch (shapeType) {
            case 'circle':
                return new Circle(radius);
            case 'rectangle':
                return new Rectangle(width, height);
            case 'triangle':
                // 假设三角形以底和高定义
                return new Triangle(width, height);
            default:
                throw new Error('Invalid shape type');
        }
    }
}

// 示例用法
const circle = ShapeFactory.getShape('circle', 0, 0, 5);
console.log(`Circle Area: ${circle.calculateArea()}`);

额外分享

码小课网站中有更多关于面向对象编程、设计模式、算法和数据结构等相关内容分享给大家学习,欢迎大家访问并深入学习。

推荐面试题