单例模式
Python 实现单例模式的示例代码:
class Singleton:
__instance = None
def __init__(self):
if Singleton.__instance != None:
raise Exception("Singleton can only be initialized once.")
else:
Singleton.__instance = self
@staticmethod
def getInstance():
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
工厂模式
Python 实现工厂模式的示例代码:
class Product:
def doSomething(self):
pass
class ProductA(Product):
def doSomething(self):
print("Product A does something.")
class ProductB(Product):
def doSomething(self):
print("Product B does something.")
class Factory:
def createProduct(self, productType):
if productType == "A":
return ProductA()
elif productType == "B":
return ProductB()
else:
raise ValueError("Invalid product type")
抽象工厂模式
Python 实现抽象工厂模式的示例代码:
class Button:
def paint(self):
pass
class TextField:
def paint(self):
pass
class WinButton(Button):
def paint(self):
print("Win button painted.")
class WinTextField(TextField):
def paint(self):
print("Win text field painted.")
class MacButton(Button):
def paint(self):
print("Mac button painted.")
class MacTextField(TextField):
def paint(self):
print("Mac text field painted.")
class GUIFactory:
def createButton(self):
pass
def createTextField(self):
pass
class WinGUIFactory(GUIFactory):
def createButton(self):
return WinButton()
def createTextField(self):
return WinTextField()
class MacGUIFactory(GUIFactory):
def createButton(self):
return MacButton()
def createTextField(self):
return MacTextField()
建造者模式
Python 实现建造者模式的示例代码:
class Product:
def __init__(self):
self.part1 = ""
self.part2 = ""
self.part3 = ""
def __str__(self):
return f"Part 1: {self.part1}, Part 2: {self.part2}, Part 3: {self.part3}"
class Builder:
def buildPart1(self):
pass
def buildPart2(self):
pass
def buildPart3(self):
pass
def getProduct(self):
pass
class ConcreteBuilder(Builder):
def __init__(self):
self.product = Product()
def buildPart1(self):
self.product.part1 = "Part 1"
def buildPart2(self):
self.product.part2 = "Part 2"
def buildPart3(self):
self.product.part3 = "Part 3"
def getProduct(self):
return self.product
class Director:
def __init__(self, builder):
self.builder = builder
def construct(self):
self.builder.buildPart1()
self.builder.buildPart2()
self.builder.buildPart3()
原型模式
Python 实现原型模式的示例代码:
import copy
class Prototype:
def clone(self):
pass
class ConcretePrototype(Prototype):
def __init__(self, name):
self.name = name
def setName(self, name):
self.name = name
def getName(self):
return self.name
def clone(self):
return copy.deepcopy(self)
这些示例代码可以帮助您更好地理解各种设计模式的实现方式和应用场景。请注意,这里给出的示例可能不是最优的实现方法,而且它们只是为了演示如何使用Python来实现设计模式的基本原则。
2023/4/1 23:55:47
继续
2023/4/1 23:57:06
适配器模式
Python 实现适配器模式的示例代码:
class Target:
def request(self):
pass
class Adaptee:
def specificRequest(self):
pass
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def request(self):
self.adaptee.specificRequest()
桥接模式
Python 实现桥接模式的示例代码:
class Implementor:
def operation(self):
pass
class ConcreteImplementor1(Implementor):
def operation(self):
print("ConcreteImplementor1 operation")
class ConcreteImplementor2(Implementor):
def operation(self):
print("ConcreteImplementor2 operation")
class Abstraction:
def __init__(self, implementor):
self.implementor = implementor
def operation(self):
self.implementor.operation()
class RefinedAbstraction(Abstraction):
def operation(self):
super().operation()
print("RefinedAbstraction operation")
装饰器模式
Python 实现装饰器模式的示例代码:
class Component:
def operation(self):
pass
class ConcreteComponent(Component):
def operation(self):
print("ConcreteComponent operation")
class Decorator(Component):
def __init__(self, component):
self.component = component
def operation(self):
self.component.operation()
class ConcreteDecoratorA(Decorator):
def operation(self):
super().operation()
print("ConcreteDecoratorA operation")
class ConcreteDecoratorB(Decorator):
def operation(self):
super().operation()
print("ConcreteDecoratorB operation")
外观模式
Python 实现外观模式的示例代码:
class Subsystem1:
def operation1(self):
pass
class Subsystem2:
def operation2(self):
pass
class Facade:
def __init__(self, subsystem1, subsystem2):
self.subsystem1 = subsystem1
self.subsystem2 = subsystem2
def operation(self):
self.subsystem1.operation1()
self.subsystem2.operation2()
享元模式
Python 实现享元模式的示例代码:
class Flyweight:
def operation(self, extrinsicState):
pass
class ConcreteFlyweight(Flyweight):
def operation(self, extrinsicState):
print(f"ConcreteFlyweight: {extrinsicState}")
class FlyweightFactory:
flyweights = {}
def getFlyweight(self, key):
if key not in self.flyweights:
self.flyweights[key] = ConcreteFlyweight()
return self.flyweights[key]
组合模式
Python 实现组合模式的示例代码:
class Component:
def operation(self):
pass
class Leaf(Component):
def operation(self):
print("Leaf operation")
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 Client:
def main(self):
leaf = Leaf()
composite = Composite()
composite.add(leaf)
composite.operation()
策略模式
Python 实现策略模式的示例代码:
class Strategy:
def operation(self):
pass
class ConcreteStrategyA(Strategy):
def operation(self):
print("ConcreteStrategyA operation")
class ConcreteStrategyB(Strategy):
def operation(self):
print("ConcreteStrategyB operation")
class Context:
def __init__(self, strategy):
self.strategy = strategy
def setStrategy(self, strategy):
self.strategy = strategy
def executeStrategy(self):
self.strategy.operation()
模板方法模式
Python 实现模板方法模式的示例代码:
class AbstractClass:
def templateMethod(self):
self.operation1()
self.operation2()
def operation1(self):
pass
def operation2(self):
pass
class ConcreteClass(AbstractClass):
def operation1(self):
print("ConcreteClass operation1")
def operation2(self):
print("ConcreteClass operation2")
观察者模式
Python 实现观察者模式的示例代码:
class Observable:
observers = []
def addObserver(self,
2023/4/1 23:57:47
继续
2023/4/1 23:58:18
observer):
self.observers.append(observer)
def removeObserver(self, observer):
self.observers.remove(observer)
def notifyObservers(self):
for observer in self.observers:
observer.update()
class Observer:
def update(self):
pass
class ConcreteObservable(Observable):
def init(self):
self.state = 0
def getState(self):
return self.state
def setState(self, state):
self.state = state
self.notifyObservers()
class ConcreteObserver(Observer):
def init(self, observable):
self.observable = observable
def update(self):
print(f"ConcreteObserver updated with state {self.observable.getState()}")
observable = ConcreteObservable()
observer1 = ConcreteObserver(observable)
observer2 = ConcreteObserver(observable)
observable.addObserver(observer1)
observable.addObserver(observer2)
observable.setState(1)
15. 迭代器模式
Python 实现迭代器模式的示例代码:
class Iterator:
def hasNext(self):
pass
def next(self):
pass
class Aggregate:
def createIterator(self):
pass
class ConcreteIterator(Iterator):
def init(self, aggregate):
self.aggregate = aggregate
self.index = 0
def hasNext(self):
return self.index < len(self.aggregate.items)
def next(self):
if not self.hasNext():
raise StopIteration("No more items.")
item = self.aggregate.items[self.index]
self.index += 1
return item
class ConcreteAggregate(Aggregate):
def init(self):
self.items = []
def createIterator(self):
return ConcreteIterator(self)
def addItem(self, item):
self.items.append(item)
这些示例代码展示了各种设计模式的实现方式。请注意,这些示例可能不是最优的实现方法。设计模式的实现取决于您的具体需求和系统架构。因此,在选择设计模式时,请务必仔细考虑您的需求并选择最适合您的方案。
2023/4/1 23:58:24
继续
2023/4/1 23:59:22
责任链模式
Python 实现责任链模式的示例代码:
class Handler:
def setSuccessor(self, successor):
pass
def handleRequest(self, request):
pass
class ConcreteHandler1(Handler):
def setSuccessor(self, successor):
self.successor = successor
def handleRequest(self, request):
if request == "R1":
print("ConcreteHandler1 handled the request.")
elif self.successor != None:
self.successor.handleRequest(request)
class ConcreteHandler2(Handler):
def setSuccessor(self, successor):
self.successor = successor
def handleRequest(self, request):
if request == "R2":
print("ConcreteHandler2 handled the request.")
elif self.successor != None:
self.successor.handleRequest(request)
命令模式
Python 实现命令模式的示例代码:
class Command:
def execute(self):
pass
class Receiver:
def action(self):
pass
class ConcreteCommand(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action()
class Invoker:
def setCommand(self, command):
self.command = command
def executeCommand(self):
self.command.execute()
备忘录模式
Python 实现备忘录模式的示例代码:
class Memento:
def getState(self):
pass
def setState(self, state):
pass
class Originator:
def setState(self, state):
self.state = state
def createMemento(self):
memento = ConcreteMemento()
memento.setState(self.state)
return memento
def restoreMemento(self, memento):
self.state = memento.getState()
class ConcreteMemento(Memento):
def getState(self):
return self.state
def setState(self, state):
self.state = state
状态模式
Python 实现状态模式的示例代码:
class State:
def handle(self):
pass
class ConcreteStateA(State):
def handle(self):
print("ConcreteStateA handled the request.")
return ConcreteStateB()
class ConcreteStateB(State):
def handle(self):
print("ConcreteStateB handled the request.")
return ConcreteStateA()
class Context:
def __init__(self, state):
self.state = state
def setState(self, state):
self.state = state
def request(self):
self.state = self.state.handle()
访问者模式
Python 实现访问者模式的示例代码:
class Visitor:
def visitConcreteElementA(self, elementA):
pass
def visitConcreteElementB(self, elementB):
pass
class Element:
def accept(self, visitor):
pass
class ConcreteElementA(Element):
def accept(self, visitor):
visitor.visitConcreteElementA(self)
class ConcreteElementB(Element):
def accept(self, visitor):
visitor.visitConcreteElementB(self)
class ConcreteVisitor(Visitor):
def visitConcreteElementA(self, elementA):
print("ConcreteVisitor visited ConcreteElementA.")
def visitConcreteElementB(self, elementB):
print("ConcreteVisitor visited ConcreteElementB.")
这些示例代码展示了各种设计模式的实现方式。请注意,这些示例可能不是最优的实现方法。设计模式的实现取决于您的具体需求和系统架构。因此,在选择设计模式时,请务必仔细考虑您的需求并选择最适合您的方案。
2023/4/1 23:59:28
继续
2023/4/2 00:00:28
中介者模式
Python 实现中介者模式的示例代码:
class Mediator:
def notify(self, sender, event):
pass
class Colleague:
def __init__(self, mediator):
self.mediator = mediator
def fireEvent(self, event):
self.mediator.notify(self, event)
class ConcreteMediator(Mediator):
def __init__(self, colleague1, colleague2):
self.colleague1 = colleague1
self.colleague2 = colleague2
def notify(self, sender, event):
if sender == self.colleague1:
print(f"Colleague1 triggered {event}.")
elif sender == self.colleague2:
print(f"Colleague2 triggered {event}.")
class ConcreteColleague1(Colleague):
def triggerEvent(self):
self.fireEvent("ConcreteColleague1 Event")
class ConcreteColleague2(Colleague):
def triggerEvent(self):
self.fireEvent("ConcreteColleague2 Event")
解释器模式
Python 实现解释器模式的示例代码:
class Context:
def __init__(self, input):
self.input = input
self.output = 0
class AbstractExpression:
def interpret(self, context):
pass
class TerminalExpression(AbstractExpression):
def interpret(self, context):
context.output = int(context.input)
class NonterminalExpression(AbstractExpression):
def __init__(self, expression1, expression2):
self.expression1 = expression1
self.expression2 = expression2
def interpret(self, context):
self.expression1.interpret(context)
self.expression2.interpret(context)
context.output = context.output * 2
工厂方法模式
Python 实现工厂方法模式的示例代码:
class Creator:
def factoryMethod(self):
pass
def operation(self):
product = self.factoryMethod()
print(f"{product.operation()}")
class Product:
def operation(self):
pass
class ConcreteProductA(Product):
def operation(self):
return "ConcreteProductA operation"
class ConcreteProductB(Product):
def operation(self):
return "ConcreteProductB operation"
class ConcreteCreatorA(Creator):
def factoryMethod(self):
return ConcreteProductA()
class ConcreteCreatorB(Creator):
def factoryMethod(self):
return ConcreteProductB()
抽象工厂模式
Python 实现抽象工厂模式的示例代码:
class AbstractFactory:
def createProductA(self):
pass
def createProductB(self):
pass
class ConcreteFactory1(AbstractFactory):
def createProductA(self):
return ConcreteProductA1()
def createProductB(self):
return ConcreteProductB1()
class ConcreteFactory2(AbstractFactory):
def createProductA(self):
return ConcreteProductA2()
def createProductB(self):
return ConcreteProductB2()
class AbstractProductA:
def operationA(self):
pass
class ConcreteProductA1(AbstractProductA):
def operationA(self):
return "ConcreteProductA1 operationA"
class ConcreteProductA2(AbstractProductA):
def operationA(self):
return "ConcreteProductA2 operationA"
class AbstractProductB:
def operationB(self):
pass
class ConcreteProductB1(AbstractProductB):
def operationB(self):
return "ConcreteProductB1 operationB"
class ConcreteProductB2(AbstractProductB):
def operationB(self):
return "ConcreteProductB2 operationB"
21种设计模式Python示例代码
最新推荐文章于 2024-02-17 14:35:06 发布