You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
# 如果有一个选择结构来决定实现不同的类,再面向对象设计里面一般把这个选择做成一个类,叫做工厂模式
|
|
|
|
|
# 定义一个ProductFactory类,用于创建不同类型的商品实例(如电子产品、书籍等)。具体的产品由子类实现。
|
|
|
|
|
#
|
|
|
|
|
|
|
|
|
|
class Product:
|
|
|
|
|
def __init__(self, name, price):
|
|
|
|
|
self.name = name
|
|
|
|
|
self.price = price
|
|
|
|
|
|
|
|
|
|
class Electronic(Product):
|
|
|
|
|
def __init__(self, name, price, brand):
|
|
|
|
|
super().__init__(name, price)
|
|
|
|
|
self.brand = brand
|
|
|
|
|
|
|
|
|
|
class Book(Product):
|
|
|
|
|
def __init__(self, name, price, author):
|
|
|
|
|
super().__init__(name, price)
|
|
|
|
|
self.author = author
|
|
|
|
|
|
|
|
|
|
class ProductFactory:
|
|
|
|
|
@staticmethod
|
|
|
|
|
def create_product(product_type, *args, **kwargs):
|
|
|
|
|
if product_type == 'electronic':
|
|
|
|
|
return Electronic(*args, **kwargs)
|
|
|
|
|
elif product_type == 'book':
|
|
|
|
|
return Book(*args, **kwargs)
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError("Invalid product type")
|
|
|
|
|
|
|
|
|
|
# 使用工厂方法创建产品
|
|
|
|
|
product = ProductFactory.create_product('book', 'Python编程艺术', 50.0, 'Mark Lutz')
|