当前位置: 首页 > news >正文

做网站付费流程建网站是什么技术

做网站付费流程,建网站是什么技术,互联网公司裁员,电子商务网站的建设流程图目录 创建型模式简单工厂模式工厂方法模式抽象工厂模式单例模式原型模式建造者模式 结构型模式适配器模式桥接模式组合模式装饰器模式外观模式享元模式代理模式 行为型模式职责链模式命令模式解释器模式迭代器模式中介者模式备忘录模式观察者模式状态模式策略模式模板方法模式访… 目录 创建型模式简单工厂模式工厂方法模式抽象工厂模式单例模式原型模式建造者模式 结构型模式适配器模式桥接模式组合模式装饰器模式外观模式享元模式代理模式 行为型模式职责链模式命令模式解释器模式迭代器模式中介者模式备忘录模式观察者模式状态模式策略模式模板方法模式访问者模式 Reference 创建型模式 简单工厂模式 实现 from abc import abstractmethod, ABCMetaclass Product(metaclass ABCMeta):def __init__(self):passabstractmethoddef do(self):passclass ConcreteProductA(Product):def __init__(self):super().__init__()def do(self):print([ConcreteProductA]do())class ConcreteProductB(Product):def __init__(self):super().__init__()def do(self):print([ConcreteProductB]do())class SimpleFactory:staticmethoddef create_product(arg):if A str.upper(arg):return ConcreteProductA()elif B str.upper(arg):return ConcreteProductB()else:raise Exception(fUnsupported: {arg})if __name__ __main__:product_a SimpleFactory.create_product(A)product_a.do()product_b SimpleFactory.create_product(b)product_b.do() 优点 简单工厂模式提供了专门的工厂类用于创建对象将对象的创建和对象的使用分离开。客户端只需提供想要的产品属性简单工厂就可以创建出来具体的产品供客户端使用客户端不用关心创建逻辑。缺点 工厂类集中了所有产品的创建逻辑职责过重一旦不能正常工作整个系统都要受到影响。系统扩展困难一旦添加新产品就得修改工厂逻辑在产品类型较多时有可能造成工厂逻辑过于复杂不利于系统的扩展和维护。适用场景 工厂类负责创建的对象比较少不会造成工厂方法中的业务逻辑太过复杂。 工厂方法模式 实现 from abc import abstractmethod, ABCMetaclass Product(metaclass ABCMeta):def __init__(self):passabstractmethoddef do(self):passclass ConcreteProductA(Product):def __init__(self):super().__init__()def do(self):print([ConcreteProductA]do())class ConcreteProductB(Product):def __init__(self):super().__init__()def do(self):print([ConcreteProductB]do())class Factory(metaclass ABCMeta):def __init__(self):passabstractmethoddef create_product(self):passclass FactoryA(Factory):def __init__(self):super().__init__()def create_product(self):return ConcreteProductA()class FactoryB(Factory):def __init__(self):super().__init__()def create_product(self):return ConcreteProductB()if __name__ __main__:factoryA FactoryA()productA factoryA.create_product()productA.do()factoryB FactoryB()productB factoryB.create_product()productB.do()优点 继承了简单工厂模式的优点用户只需要关心所需产品对应的工厂。扩展性高如果想增加一个产品只要扩展一个工厂类就可以符合“开闭原则”。 缺点 每次增加一个产品时都需要增加一个具体类和对象实现工厂使得系统中类的个数成倍增加在一定程度上增加了系统的复杂度。 使用场景 数据库访问当用户不知道最后系统采用哪一类数据库以及数据库可能有变化时。 抽象工厂模式 产品族小米的手机电视、华为的手机电视 产品等级结构手机的小米华为电视的小米华为 增加产品族比如OPPO的手机电视只需增加OPPO工厂及对应具体产品即可符合“开闭原则”但增加产品等级结构比如耳机的小米华为就需要修改所有工厂违反“开闭原则”。 from abc import abstractmethod, ABCMetaclass ProductA(metaclass ABCMeta):def __init__(self):passabstractmethoddef do(self):passclass ConcreteProductA1(ProductA):def __init__(self):super().__init__()def do(self):print([ConcreteProductA1]do())class ConcreteProductA2(ProductA):def __init__(self):super().__init__()def do(self):print([ConcreteProductA2]do())class ProductB(metaclass ABCMeta):def __init__(self):passabstractmethoddef do(self):passclass ConcreteProductB1(ProductB):def __init__(self):super().__init__()def do(self):print([ConcreteProductB1]do())class ConcreteProductB2(ProductB):def __init__(self):super().__init__()def do(self):print([ConcreteProductB2]do())class Factory(metaclass ABCMeta):def __init__(self):passabstractmethoddef create_productA(self):passabstractmethoddef create_productB(self):passclass Factory1(Factory):def __init__(self):super().__init__()def create_productA(self):return ConcreteProductA1()def create_productB(self):return ConcreteProductB1()class Factory2(Factory):def __init__(self):super().__init__()def create_productA(self):return ConcreteProductA2()def create_productB(self):return ConcreteProductB2()if __name__ __main__:factory1 Factory1()productA1 factory1.create_productA()productB1 factory1.create_productB()productA1.do()productB1.do()factory2 Factory2()productA2 factory2.create_productA()productB2 factory2.create_productB()productA2.do()productB2.do()单例模式 class Singleton:def __new__(cls, *args, **kwargs):if not hasattr(cls, _instance):cls._instance super(Singleton, cls).__new__(cls)return cls._instanceif __name__ __main__:singleton1 Singleton(1, x 1)singleton2 Singleton(2, x 2)print(id(singleton1) id(singleton2)) 原型模式 浅克隆 深克隆 from abc import ABCMeta, abstractmethod import copyclass Prototype(metaclass ABCMeta):abstractmethoddef clone(self):passclass PrototypeA(Prototype):def clone(self):return copy.copy(self)class PrototypeB(Prototype):def clone(self):return copy.copy(self)if __name__ __main__:prototypeA PrototypeA()prototypeACopy prototypeA.clone()建造者模式 from abc import ABCMeta, abstractmethodclass Product:def __init__(self, a None, b None, c None):self.a aself.b bself.c cdef __str__(self):return fProduct[a{self.a}, b{self.b}, c{self.c}]class Builder(metaclass ABCMeta):abstractmethoddef buildA(self):passabstractmethoddef buildB(self):passabstractmethoddef buildC(self):passabstractmethoddef getResult(self):passclass ConcreteBuilder(Builder):def __init__(self):self.product Product()def buildA(self):self.product.a Aprint(fbuild part {self.product.a})def buildB(self):self.product.b Bprint(fbuild part {self.product.b})def buildC(self):self.product.c Cprint(fbuild part {self.product.c})def getResult(self):return self.productclass Director:def __init__(self, builder):self.builder builderdef construct(self):self.builder.buildA()self.builder.buildB()self.builder.buildC()return self.builder.getResult()if __name__ __main__:builder ConcreteBuilder()director Director(builder)product director.construct()print(product)结构型模式 适配器模式 我的笔记本电脑的工作电压是20V而我国的家庭用电是220V如何让20V的笔记本电脑能够在220V的电压下工作答案是引入一个电源适配器(AC Adapter)俗称充电器或变压器。 适配器模式(Adapter Pattern)将一个接口转换成客户希望的另一个接口使接口不兼容的那些类可以一起工作。以电源适配器Adapter为例Target是电脑目前支持的22V接口Adaptee是220V插口。 对象适配器 from abc import ABCMeta, abstractmethodclass Target(metaclass ABCMeta):abstractmethoddef request(self):print(can use 20V)class Adaptee:def specificRequest(self):print(can use 220V)class Adapter(Target):def __init__(self):self.adaptee Adaptee()def request(self):print(Before)super().request()print()print(Now)print(fAdapter, converting from 20V to 220V, ... , done)self.adaptee.specificRequest()if __name__ __main__:adapter Adapter()adapter.request()类适配器 from abc import ABCMeta, abstractmethodclass Target(metaclass ABCMeta):abstractmethoddef request(self):print(can use 20V)class Adaptee:def specificRequest(self):print(can use 220V)class Adapter(Target, Adaptee):def request(self):print(Before)super().request()print()print(Now)print(fAdapter, converting from 20V to 220V, ... , done)self.specificRequest() # super().specificRequest()if __name__ __main__:adapter Adapter()adapter.request()桥接模式 将一个事物的两个维度分离使其都可以独立地变化。 from abc import ABCMeta, abstractmethodclass Shape(metaclass ABCMeta):def __init__(self, color):self.color colorabstractmethoddef draw(self):passclass Rectangle(Shape):def draw(self):self.shape_name rectangleself.color.paint()print(fdraw a {self.color.color_name} {self.shape_name})class Circle(Shape):def draw(self):self.shape_name circleself.color.paint()print(fdraw a {self.color.color_name} {self.shape_name})class Color(metaclass ABCMeta):abstractmethoddef paint(self):passclass Red(Color):def paint(self):self.color_name redclass Blue(Color):def paint(self):self.color_name blueif __name__ __main__:shape Circle(Red())shape.draw()组合模式 将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。 from abc import ABCMeta, abstractmethodclass AbstractFile(metaclass ABCMeta):abstractmethoddef add(self, file):passabstractmethoddef remove(self, file):passabstractmethoddef getChild(self, i):passabstractmethoddef traverse(self, deep):passclass TextFile(AbstractFile):def __init__(self, name):self.name namedef add(self, file):raise Exception(unsupported)def remove(self, file):raise Exception(unsupported)def getChild(self, i):raise Exception(unsupported)def traverse(self, deep):for i in range(deep):print(\t, end)print(ftext:{self.name})class ImageFile(AbstractFile):def __init__(self, name):self.name namedef add(self, file):raise Exception(unsupported)def remove(self, file):raise Exception(unsupported)def getChild(self, i):raise Exception(unsupported)def traverse(self, deep):for i in range(deep):print(\t, end)print(fimage:{self.name})class Folder(AbstractFile):def __init__(self, name):self.name nameself.file_list []def add(self, file):self.file_list.append(file)def remove(self, file):self.file_list.remove(file)def getChild(self, i):return self.file_list.index(i)def traverse(self, deep):for i in range(deep):print(\t, end)print(self.name)for f in self.file_list:f.traverse(deep 1)if __name__ __main__:folder1 Folder(folder1)file1 TextFile(t1.txt)file2 ImageFile(i1.png)folder1.add(file1)folder1.add(file2)folder2 Folder(folder2)file3 TextFile(t2.txt)file4 ImageFile(i2.png)folder2.add(file3)folder2.add(file4)folder1.add(folder2)folder1.traverse(0)装饰器模式 装饰器模式Decorator Pattern允许向一个现有的对象添加新的功能同时又不改变其结构。它是作为现有的类的一个包装。 from abc import ABCMeta, abstractmethodclass Component(metaclass ABCMeta):abstractmethoddef operation(self):passclass ConcreteComponent(Component):def operation(self):print(ConcreteComponent.operation())class Decorator(Component):def __init__(self, component):self.component componentdef operation(self):self.component.operation()class ConcreteDecoratorA(Decorator):def __init__(self, component, state):super().__init__(component)self.state statedef operation(self):super().operation()print(fstate: {self.state})class ConcreteDecoratorB(Decorator):def operation(self):super().operation()self.added_behavior()def added_behavior(self):print(ConcreteDecoratorB.added_behavior())if __name__ __main__:component ConcreteComponent()decoratorA ConcreteDecoratorA(component, Normal)decoratorA.operation()decoratorB ConcreteDecoratorB(component)decoratorB.operation()外观模式 外观模式中一个子系统的外部与其内部的通信通过一个统一的外观类进行外观类将客户类与子系统的内部复杂性分隔开使得客户类只需要与外观角色打交道而不需要与子系统内部的很多对象打交道。 class CPU:def start(self):print(cpu start...)def stop(self):print(cpu stop...)class Memory:def start(self):print(memory start...)def stop(self):print(memory stop...)class Disk:def start(self):print(disk start...)def stop(self):print(disk stop...)class Computer:def __init__(self):self.cpu CPU()self.memory Memory()self.disk Disk()def start(self):self.cpu.start()self.memory.start()self.disk.start()def stop(self):self.cpu.stop()self.memory.stop()self.disk.stop()if __name__ __main__:computer Computer()computer.start()computer.stop()享元模式 围棋棋子只有黑白棋两种内部状态只有黑白所有黑子共享黑内部状态所有白子共享白内部状态。减少创建对象的数量而每次落子坐标不同外部状态。 from abc import abstractmethod, ABCMetaclass IgoChessman(metaclass ABCMeta):abstractmethoddef get_color(self):passdef display(self, coordinate):print(f{self.get_color()}, {coordinate.x, coordinate.y})class BlackIgoChessman(IgoChessman):def get_color(self):return blackclass WhiteIgoChessman(IgoChessman):def get_color(self):return whiteclass IgoChessmanFactory:def __new__(cls, *args, **kwargs):if not hasattr(cls, _instance):cls._instance super(IgoChessmanFactory, cls).__new__(cls)cls._instance.ht {}cls._instance.ht[black] BlackIgoChessman()cls._instance.ht[white] WhiteIgoChessman()return cls._instancedef getIgoChessman(self, color):return IgoChessmanFactory._instance.ht[color]class Coordinate:def __init__(self, x, y):self.x xself.y yif __name__ __main__:factory IgoChessmanFactory()black1 factory.getIgoChessman(black)white1 factory.getIgoChessman(white)black2 factory.getIgoChessman(black)white2 factory.getIgoChessman(white)print(black1 is black2)print(white1 is white2)black1.display(Coordinate(1, 2))white1.display(Coordinate(3, 4))black2.display(Coordinate(8, 9))white2.display(Coordinate(4, 5)) 代理模式 保护代理(Protect Proxy)控制对一个对象的访问给不同的用户提供不同级别的使用权限。 from abc import abstractmethod, ABCMeta import timeclass Searcher(metaclass ABCMeta):abstractmethoddef search(self, user_id, key_word):passclass RealSearcher(Searcher):def search(self, user_id, key_word):print(f[RealSearcher.search](use_id: {user_id}, key_word: {key_word}) and return what you want)class AccessValidator:def validate(self, user_id):print(f[AccessValidator.validate]{user_id} has access to search!)class Logger:def log(self, user_id):print(f[Logger.log]{user_id} visit at {time.strftime(%Y-%m-%d %H:%M:%S, time.localtime(time.time()))})class ProxySearcher(Searcher):def __init__(self):self.validator AccessValidator()self.logger Logger()self.searcher RealSearcher()def search(self, user_id, key_word):self.validator.validate(user_id)self.searcher.search(user_id, key_word)self.logger.log(user_id)if __name__ __main__:proxy ProxySearcher()proxy.search(Tom, iPhone) 行为型模式 职责链模式 职责链模式(Chain of Responsibility Pattern)避免请求发送者与接收者耦合在一起让多个对象都有可能接收请求将这些对象连接成一条链并且沿着这条链传递请求直到有对象处理它为止。 from abc import abstractmethod, ABCMetaclass Handler(metaclass ABCMeta):abstractmethoddef handle_leave(self, day):passdef set_successor(self, successor):self.successor successorclass GeneralManagerHandler(Handler):def handle_leave(self, day):if day 10:print(General manager approved %d days leave. % day)else:print(No approval!)class DepartmentManagerHandler(Handler):def handle_leave(self, day):if day 7:print(Department manager approved %d days leave. % day)else:self.successor.handle_leave(day)class ProjectManagerHandler(Handler):def handle_leave(self, day):if day 3:print(Project manager approved %d days leave. % day)else:self.successor.handle_leave(day)if __name__ __main__:projectManager ProjectManagerHandler()departmentManager DepartmentManagerHandler()generalManager GeneralManagerHandler()projectManager.set_successor(departmentManager)departmentManager.set_successor(generalManager)projectManager.handle_leave(8)命令模式 Invoker开关 Command电线 Receiver电灯/排风扇 命令模式可以将请求发送者和接收者完全解耦发送者与接收者之间没有直接引用关系发送请求的对象只需要知道如何发送请求而不必知道如何完成请求。 from abc import abstractmethod, ABCMetaclass Invoker:def __init__(self, wire):self.wire wiredef open(self):self.wire.execute()class Wire(metaclass ABCMeta):abstractmethoddef execute(self):passclass LampWire(Wire):def __init__(self):self.lamp_receiver LampReceiver()def execute(self):self.lamp_receiver.action()class FanWire(Wire):def __init__(self):self.fan_wire FanReceiver()def execute(self):self.fan_wire.do()class LampReceiver:def action(self):print(open the lamp)class FanReceiver:def do(self):print(open the fan) if __name__ __main__:invoker1 Invoker(LampWire())invoker1.open()invoker2 Invoker(FanWire())invoker2.open() 解释器模式 简化版四则运算解释器的实现真正实现要搞定中缀表达式求解逻辑封入Context中 from abc import abstractmethod, ABCMetaclass Expression(metaclass ABCMeta):abstractmethoddef interpret(self, context):passclass NumberExpression(Expression):def __init__(self, value):self.value valuedef interpret(self, context):return self.valueclass AddExpression(Expression):def __init__(self, left, right):self.left leftself.right rightdef interpret(self, context):return self.left.interpret(context) self.right.interpret(context)class SubtractExpression(Expression):def __init__(self, left, right):self.left leftself.right rightdef interpret(self, context):return self.left.interpret(context) - self.right.interpret(context)class Context:passif __name__ __main__:expression AddExpression(NumberExpression(10), SubtractExpression(NumberExpression(5), NumberExpression(2)))result expression.interpret(Context())print(result) 迭代器模式 在软件开发中我们经常需要使用聚合对象来存储一系列数据。聚合对象拥有两个职责一是存储数据二是遍历数据。从依赖性来看前者是聚合对象的基本职责而后者既是可变化的又是可分离的。因此可以将遍历数据的行为从聚合对象中分离出来封装在一个被称之为“迭代器”的对象中由迭代器来提供遍历聚合对象内部数据的行为这将简化聚合对象的设计更符合“单一职责原则”的要求。 迭代器模式(Iterator Pattern)提供一种方法来访问聚合对象而不用暴露这个对象的内部表示其别名为游标(Cursor)。迭代器模式是一种对象行为型模式。 在迭代器模式结构中包含聚合和迭代器两个层次结构考虑到系统的灵活性和可扩展性在迭代器模式中应用了工厂方法模式其模式结构如下图所示 from abc import ABC, abstractmethodclass Aggregate(ABC):abstractmethoddef create_iterator(self):passclass ConcreteAggregate(Aggregate):def __init__(self):self.data list(range(1, 6))self.idx 0def create_iterator(self):return ConcreteIterator(self)class Iterator(ABC):abstractmethoddef has_next(self):passabstractmethoddef next(self):passclass ConcreteIterator(Iterator):def __init__(self, aggregate):self.aggregate aggregatedef has_next(self):return self.aggregate.idx len(self.aggregate.data)def next(self):data self.aggregate.data[self.aggregate.idx]self.aggregate.idx 1return dataif __name__ __main__:aggregate ConcreteAggregate()iterator aggregate.create_iterator()while iterator.has_next():print(iterator.next())中介者模式 如果在一个系统中对象之间存在多对多的相互关系我们可以将对象之间的一些交互行为从各个对象中分离出来并集中封装在一个中介者对象中并由该中介者进行统一协调这样对象之间多对多的复杂关系就转化为相对简单的一对多关系。通过引入中介者来简化对象之间的复杂交互中介者模式是“迪米特法则”的一个典型应用。 以微信群发消息为例多人两两交互变为一对多交互实现如下 from abc import ABC, abstractmethodclass Mediator(ABC):abstractmethoddef send_msg(self, colleague, msg):passclass ConcreteMediator(Mediator):def send_msg(self, colleague, msg):print(f[{colleague.name}] {msg})class Colleague(ABC):abstractmethoddef __init__(self, name, mediator):self.mediator mediatorself.name nameabstractmethoddef send_msg(self, msg):pass class ConcreteColleague(Colleague):def __init__(self, name, mediator):super().__init__(name, mediator)def send_msg(self, msg):self.mediator.send_msg(self, msg)if __name__ __main__:mediator ConcreteMediator()colleague1 ConcreteColleague(Jack, mediator)colleague2 ConcreteColleague(Marry, mediator)colleague1.send_msg(Are you ok)colleague2.send_msg(Happy) 备忘录模式 备忘录模式提供了状态恢复机制比如下棋的悔棋就可以用备忘录模式实现。 class Chessman:def __init__(self, label, x, y):self.label labelself.x xself.y ydef set_x(self, x):self.x xdef set_y(self, y):self.y ydef display(self):print(f[{self.label}] x {self.x}, y {self.y})def save(self):return Memo(self.label, self.x, self.y)def restore(self, memo):self.label memo.labelself.x memo.xself.y memo.yclass Memo:def __init__(self, label, x, y):self.label labelself.x xself.y yclass MemoManager:def __init__(self):self.memos []def add_memo(self, memo):self.memos.append(memo)def pop_memo(self):print(Try to undo...)if(len(self.memos) 1):print(The location now is original, so you cannot undo!)return Nonereturn self.memos.pop()if __name__ __main__:manager MemoManager()chessman Chessman(CAR, 1, 1)chessman.display()memo chessman.save()manager.add_memo(memo)chessman.set_y(4)chessman.display()memo chessman.save()manager.add_memo(memo)chessman.set_x(6)chessman.display()memo manager.pop_memo()if memo is not None:chessman.restore(memo)chessman.display()memo manager.pop_memo()if memo is not None:chessman.restore(memo)chessman.display()memo manager.pop_memo()if memo is not None:chessman.restore(memo)chessman.display() 观察者模式 “红灯停绿灯行”在日常生活中交通信号灯装点着我们的城市指挥着日益拥挤的城市交通。当红灯亮起来往的汽车将停止而绿灯亮起汽车可以继续前行。在这个过程中交通信号灯是汽车更准确地说应该是汽车驾驶员的观察目标而汽车是观察者。随着交通信号灯的变化汽车的行为也将随之而变化一盏交通信号灯可以指挥多辆汽车。 观察者模式(Observer Pattern)定义对象之间的一种一对多依赖关系使得每当一个对象状态发生改变时其相关依赖对象皆得到通知并被自动更新。观察者模式的别名包括发布-订阅Publish/Subscribe模式、模型-视图Model/View模式、源-监听器Source/Listener模式或从属者Dependents模式。观察者模式是一种对象行为型模式。 from abc import ABC, abstractmethodclass Observer(ABC):def __init__(self, name):self.name nameabstractmethoddef update(msg):passclass ConcreteObserver(Observer):def __init__(self, name):super().__init__(name)def update(self, msg):print(f[{self.name}]: {msg})class Project(ABC):abstractmethoddef add_observer(self, observer):passabstractmethoddef delete_observer(self, observer):passabstractmethoddef notify(self):passclass ConcreteProject(Project):def __init__(self):self.observers []def add_observer(self, observer):self.observers.append(observer)def delete_observer(self, observer):self.observers.remove(observer)def notify(self, msg):for observer in self.observers:observer.update(msg)if __name__ __main__:traffic_light ConcreteProject()tom ConcreteObserver(Tom)lucy ConcreteObserver(Lucy)traffic_light.add_observer(tom)traffic_light.add_observer(lucy)traffic_light.notify(traffic light is red) 状态模式 点击循环调整屏幕尺寸正常、更大、最大、正常…… from abc import ABC, abstractmethodclass State(ABC):abstractmethoddef display(self):passclass NormalState(State):def display(self):print(Normal)class LargerState(State):def display(self):print(Larger)class LargestState(State):def display(self):print(Largest)class Screen:def __init__(self):self.normal_state NormalState()self.larger_state LargerState()self.largest_state LargestState()self.state self.normal_statedef on_click(self):if self.state is self.normal_state:self.state self.larger_stateelif self.state is self.larger_state:self.state self.largest_stateelse:self.state self.normal_stateself.state.display()if __name__ __main__:screen Screen()screen.on_click()screen.on_click()screen.on_click()screen.on_click() 策略模式 from abc import ABC, abstractmethodclass Strategy(ABC):abstractmethoddef algorithm(self):passclass ConcreteStategyA(Strategy):def algorithm(self):print(ConcreteStategyA)class ConcreteStategyB(Strategy):def algorithm(self):print(ConcreteStategyB)class Context:def set_stategy(self, strategy):self.strategy strategydef algorithm(self):self.strategy.algorithm()if __name__ __main__:context Context()context.set_stategy(ConcreteStategyA())context.algorithm()context.set_stategy(ConcreteStategyB())context.algorithm() 模板方法模式 from abc import ABC, abstractmethodclass Game(ABC):def play(self):self.init()self.start()self.end()abstractmethoddef init(self):passabstractmethoddef start(self):passabstractmethoddef end(self):passclass GameA(Game):def init(self):print([GameA]init...)def start(self):print([GameA]start...)def end(self):print([GameA]end...)class GameB(Game):def init(self):print([GameB]init...)def start(self):print([GameB]start...)def end(self):print([GameB]end...)if __name__ __main__:game_a GameA()game_a.play()game_b GameB()game_b.play() 访问者模式 访问者模式是一种较为复杂的行为型设计模式它包含访问者和被访问元素两个主要组成部分这些被访问的元素通常具有不同的类型且不同的访问者可以对它们进行不同的访问操作。例如处方单中的各种药品信息就是被访问的元素而划价人员和药房工作人员就是访问者。访问者模式使得用户可以在不修改现有系统的情况下扩展系统的功能为这些不同类型的元素增加新的操作。 公司中有正式工和临时工而HR和财务人员对工人的关注点不同前者关心工时计算后者关心工资计算。这个例子中工人对应ElementHR和财务人员对应Visitor。实现如下 from abc import ABC, abstractmethodclass Employee(ABC):abstractmethoddef accept(self, handler):passclass FulltimeEmployee(Employee):def __init__(self, name, weekly_wage, work_time):self.name nameself.weekly_wage weekly_wageself.work_time work_timedef accept(self, handler):handler.visit_fulltime_employee(self)class ParttimeEmployee(Employee):def __init__(self, name, hourly_wage, work_time):self.name nameself.hourly_wage hourly_wageself.work_time work_timedef accept(self, handler):handler.visit_parttime_employee(self)class Department(ABC):abstractmethoddef visit_fulltime_employee(self, employee):passabstractmethoddef visit_parttime_employee(self, employee):passclass FinanceDepartment(Department):def visit_fulltime_employee(self, employee):if(employee.work_time 40):week_wage employee.weekly_wage (employee.work_time - 40) * 100else:week_wage employee.weekly_wage - (40 - employee.work_time) * 80if week_wage 0:week_wage 0print(fFulltime employee {employee.name}, salary {week_wage} yuan)def visit_parttime_employee(self, employee):print(fParttime employee {employee.name}, salary {employee.work_time * employee.hourly_wage} yuan)class HRDepartment(Department):def visit_fulltime_employee(self, employee):print(fFulltime employee {employee.name}, work time {employee.work_time} hours)if(employee.work_time 40):print(fFulltime employee {employee.name}, overtime {employee.work_time - 40} hours)else:print(fFulltime employee {employee.name}, vocation time {40 - employee.work_time} hours)def visit_parttime_employee(self, employee):print(fParttime employee {employee.name}, work time {employee.work_time} hours)class EmployeeList:def __init__(self):self.employees []def add(self, employee):self.employees.append(employee)def accept(self, handler):for employee in self.employees:employee.accept(handler)if __name__ __main__:employee_list EmployeeList()employee1 FulltimeEmployee(employee1, 1000, 30)employee2 FulltimeEmployee(employee2, 3000, 50)employee3 ParttimeEmployee(employee3, 30, 15)employee4 ParttimeEmployee(employee4, 20, 10)employee_list.add(employee1)employee_list.add(employee2)employee_list.add(employee3)employee_list.add(employee4)department1 HRDepartment()department2 FinanceDepartment()employee_list.accept(department1)employee_list.accept(department2) Reference [1] 史上最全设计模式导学目录完整版
文章转载自:
http://www.morning.mqxrx.cn.gov.cn.mqxrx.cn
http://www.morning.kxnjg.cn.gov.cn.kxnjg.cn
http://www.morning.iqcge.com.gov.cn.iqcge.com
http://www.morning.kdnrc.cn.gov.cn.kdnrc.cn
http://www.morning.lflnb.cn.gov.cn.lflnb.cn
http://www.morning.qydgk.cn.gov.cn.qydgk.cn
http://www.morning.qbxdt.cn.gov.cn.qbxdt.cn
http://www.morning.zplzj.cn.gov.cn.zplzj.cn
http://www.morning.xzlp.cn.gov.cn.xzlp.cn
http://www.morning.bpkqd.cn.gov.cn.bpkqd.cn
http://www.morning.jkwwm.cn.gov.cn.jkwwm.cn
http://www.morning.brtxg.cn.gov.cn.brtxg.cn
http://www.morning.hgtr.cn.gov.cn.hgtr.cn
http://www.morning.qwdqq.cn.gov.cn.qwdqq.cn
http://www.morning.rdng.cn.gov.cn.rdng.cn
http://www.morning.nxrgl.cn.gov.cn.nxrgl.cn
http://www.morning.ykrkq.cn.gov.cn.ykrkq.cn
http://www.morning.tjndb.cn.gov.cn.tjndb.cn
http://www.morning.dytqf.cn.gov.cn.dytqf.cn
http://www.morning.qnbzs.cn.gov.cn.qnbzs.cn
http://www.morning.lhhkp.cn.gov.cn.lhhkp.cn
http://www.morning.gybnk.cn.gov.cn.gybnk.cn
http://www.morning.nbrdx.cn.gov.cn.nbrdx.cn
http://www.morning.zrhhb.cn.gov.cn.zrhhb.cn
http://www.morning.bssjz.cn.gov.cn.bssjz.cn
http://www.morning.wyzby.cn.gov.cn.wyzby.cn
http://www.morning.yrycb.cn.gov.cn.yrycb.cn
http://www.morning.wjtxt.cn.gov.cn.wjtxt.cn
http://www.morning.kpbq.cn.gov.cn.kpbq.cn
http://www.morning.sgpny.cn.gov.cn.sgpny.cn
http://www.morning.krfpj.cn.gov.cn.krfpj.cn
http://www.morning.nzfqw.cn.gov.cn.nzfqw.cn
http://www.morning.ndtzy.cn.gov.cn.ndtzy.cn
http://www.morning.mcgsq.cn.gov.cn.mcgsq.cn
http://www.morning.wbllx.cn.gov.cn.wbllx.cn
http://www.morning.tlpgp.cn.gov.cn.tlpgp.cn
http://www.morning.hmgqy.cn.gov.cn.hmgqy.cn
http://www.morning.lxbml.cn.gov.cn.lxbml.cn
http://www.morning.lwgrf.cn.gov.cn.lwgrf.cn
http://www.morning.nzdks.cn.gov.cn.nzdks.cn
http://www.morning.xxfxxf.cn.gov.cn.xxfxxf.cn
http://www.morning.wbfly.cn.gov.cn.wbfly.cn
http://www.morning.uycvv.cn.gov.cn.uycvv.cn
http://www.morning.wnjwb.cn.gov.cn.wnjwb.cn
http://www.morning.jnkng.cn.gov.cn.jnkng.cn
http://www.morning.pqwhk.cn.gov.cn.pqwhk.cn
http://www.morning.xbyyd.cn.gov.cn.xbyyd.cn
http://www.morning.qlznd.cn.gov.cn.qlznd.cn
http://www.morning.ykbgs.cn.gov.cn.ykbgs.cn
http://www.morning.btqrz.cn.gov.cn.btqrz.cn
http://www.morning.pzjrm.cn.gov.cn.pzjrm.cn
http://www.morning.rnribht.cn.gov.cn.rnribht.cn
http://www.morning.qptbn.cn.gov.cn.qptbn.cn
http://www.morning.joinyun.com.gov.cn.joinyun.com
http://www.morning.kmqms.cn.gov.cn.kmqms.cn
http://www.morning.fpxsd.cn.gov.cn.fpxsd.cn
http://www.morning.wfbs.cn.gov.cn.wfbs.cn
http://www.morning.xwbld.cn.gov.cn.xwbld.cn
http://www.morning.qhqgk.cn.gov.cn.qhqgk.cn
http://www.morning.krhkb.cn.gov.cn.krhkb.cn
http://www.morning.cpmwg.cn.gov.cn.cpmwg.cn
http://www.morning.xjkfb.cn.gov.cn.xjkfb.cn
http://www.morning.rftk.cn.gov.cn.rftk.cn
http://www.morning.tnbsh.cn.gov.cn.tnbsh.cn
http://www.morning.rshkh.cn.gov.cn.rshkh.cn
http://www.morning.dpsyr.cn.gov.cn.dpsyr.cn
http://www.morning.gjcdr.cn.gov.cn.gjcdr.cn
http://www.morning.mbmtn.cn.gov.cn.mbmtn.cn
http://www.morning.bfmq.cn.gov.cn.bfmq.cn
http://www.morning.qttft.cn.gov.cn.qttft.cn
http://www.morning.kstgt.cn.gov.cn.kstgt.cn
http://www.morning.nhzxd.cn.gov.cn.nhzxd.cn
http://www.morning.xqxrm.cn.gov.cn.xqxrm.cn
http://www.morning.snjpj.cn.gov.cn.snjpj.cn
http://www.morning.hcxhz.cn.gov.cn.hcxhz.cn
http://www.morning.yongkangyiyuan-pfk.com.gov.cn.yongkangyiyuan-pfk.com
http://www.morning.bydpr.cn.gov.cn.bydpr.cn
http://www.morning.zpnfc.cn.gov.cn.zpnfc.cn
http://www.morning.gjmll.cn.gov.cn.gjmll.cn
http://www.morning.ldnrf.cn.gov.cn.ldnrf.cn
http://www.tj-hxxt.cn/news/281374.html

相关文章:

  • 东营网站排名扬州做公司网站
  • 商务门户网站怎么做建设wap手机网站
  • 织梦网站内部优化网站可以制作ios
  • 我的网站首页打不开如何去门户网站做推广呢
  • 网站建设a云世家网络创办一个网站能挣钱吗
  • 全美网站建设网站建设建设公司有哪些
  • 南京网站建设cnee谷德设计网展示设计
  • 全球网站流量排名查询国外做的比较好的展台网站
  • asp.net网站项目wordpress 强大
  • 佛山做外贸网站渠道网页设计基础实训计划
  • 手机上怎么做自己的网站谁做网站做的比较可信
  • 网站开发费算无形资产吗营销策划方案怎么写
  • 网站开发推广渠道哪些网站可以免费申请
  • 无极领域0基础12天精通网站建设asp.net网站设计
  • 手机制作网站主页软件免费网站建设加盟
  • 有哪些做短租的网站怀化网站建设怎么收费
  • 列表形式网站为网站做一则广告语
  • 运城推广型网站建设网站教程制作
  • 360网站在系统那里福州企业自助建站
  • 个人简约网站模板网站广告
  • 江苏易销 网站建设哪些软件可以做网站
  • 做网站怎么那么难图片设计网站推荐
  • 浙江做网站公司排名无货源电商软件app
  • wordpress站点安装广州住建厅官方网站
  • 电子商务网站平台开发建设方案做国外贸易哪个网站好
  • 网站备案 快速网站流量平台
  • 网站建设公司企业文化企业网站系统建设需求调研表
  • 网站建设解决方案ppt模板富德生命人寿保险公司官方网站保单查询
  • 个人做外包网站多少钱制作网页与网站
  • 语言网站开发企业网站建设经济效益分析