在设计应用程序时,不同的请求类型可能需要不同的设计模式来处理。以下是几种常见的请求类型及其对应的设计模式以及代码示例。
class Product:
def __init__(self, name):
self.name = name
class ProductFactory:
def create_product(self, name):
return Product(name)
# 使用工厂模式创建对象
factory = ProductFactory()
product = factory.create_product("Example")
class Component:
def operation(self):
pass
class Composite(Component):
def __init__(self):
self.children = []
def add(self, component):
self.children.append(component)
def remove(self, component):
self.children.remove(component)
def operation(self):
for child in self.children:
child.operation()
class Leaf(Component):
def operation(self):
print("Leaf operation")
# 使用组合模式处理组合对象
composite = Composite()
composite.add(Leaf())
composite.add(Leaf())
composite.operation()
class Strategy:
def execute(self):
pass
class ConcreteStrategyA(Strategy):
def execute(self):
print("Strategy A")
class ConcreteStrategyB(Strategy):
def execute(self):
print("Strategy B")
class Context:
def __init__(self, strategy):
self.strategy = strategy
def execute_strategy(self):
self.strategy.execute()
# 使用策略模式处理行为请求
context = Context(ConcreteStrategyA())
context.execute_strategy()
context.strategy = ConcreteStrategyB()
context.execute_strategy()
以上是几种常见请求类型的设计模式选择及其代码示例。根据具体的需求和场景,还可以选择其他适合的设计模式来处理不同类型的请求。