• Design Pattern (GoF)


    1. Factory

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class Burger:
        def __init__(self, ingredients):
            self.ingredients = ingredients
            
        def print(self):
            print(self.ingredients)
            
    class BurgerFactory:
        def createCheeseBurger(self):
            ingredients = ["bun","cheese","beef-patty"]
            return Burger(ingredients)
            
        def createDeluxeCheeseBurger(self):
            ingredients = ["bun","tomatoe","lettuce","cheese","beef-patty"]
            return Burger(ingredients)
            
        def createVeganBurger(self):
            ingredients = ["bun","special-sauce","veggie-patty"]
            return Burger(ingredients)
    
    burgerFactory = BurgerFactory()
    burgerFactory.createCheeseBurger().print()
    burgerFactory.createDeluxeCheeseBurger().print()
    burgerFactory.createVeganBurger().print()
    
    # output
    ['bun', 'cheese', 'beef-patty']
    ['bun', 'tomatoe', 'lettuce', 'cheese', 'beef-patty']
    ['bun', 'special-sauce', 'veggie-patty']
    > 
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    2. Builder

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class Burger:
        def __init__(self):
            self.buns = None
            self.patty = None
            self.cheese = None
        
        def setBuns(self,bunStyle):
            self.buns = bunStyle
            
        def setPatty(self,pattyStyle):
            self.patty = pattyStyle
            
        def setCheese(self,cheeseStyle):
            self.cheese = cheeseStyle
            
    class BurgerBuilder:
        def __init__(self):
            self.burger = Burger()
            
        def addBuns(self,bunStyle):
            self.burger.setBuns(bunStyle)
            return self
            
        def addPatty(self,pattyStyle):
            self.burger.setPatty(pattyStyle)
            return self
        
        def addCheese(self,cheeseStyle):
            self.burger.setCheese(cheeseStyle)
            return self
        
        def build(self):
            return self.burger
        
    burger = BurgerBuilder().addBuns("sesame").addPatty("fish-patty").addCheese("swiss cheese").build()
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    3. Singleton

    lol: They don’t know i can solve a leetcode hard in 30 min.

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class ApplicationState:
        instance = None
        
        def __init__(self):
            self.isLoggedIn = False
            
        @staticmethod
        def getAppState():
            if not ApplicationState.instance:
                ApplicationState.instance = ApplicationState()
                return ApplicationState.instance
                
    appState1 = ApplicationState.getAppState()
    print(appState1.isLoggedIn) # false
    
    appState2 = ApplicationState.getAppState()
    appState1.isLoggedIn = True
    
    print(appState1.isLoggedIn) # True
    print(appState2.isLoggedIn) # True
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    4. Observer / PubSub

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class YoutubeChannel:
        def __init__(self,name):
            self.name = name
            self.subscribers = []
            
        def subscribe(self,sub):
            self.subscribers.append(sub)
        
        def notify(self,event):
            for sub in self.subscribers:
                sub.sendNotification(self.name,event)
                
    from abc import ABC, abstractmethod
    
    class YoutubeSubscriber(ABC):
        @abstractmethod
        def sendNotification(self,event):
            pass
        
    class YoutubeUser(YoutubeSubscriber):
        def __init__(self,name):
            self.name = name
            
        def sendNotification(self,channel,event):
            print(f"User {self.name} received notification from {channel}:{event}")
         
    
    channel = YoutubeChannel("neetcode")
    
    channel.subscribe(YoutubeUser("sub1"))
    channel.subscribe(YoutubeUser("sub2"))
    channel.subscribe(YoutubeUser("sub3"))
    
    
    channel.notify("A new video released")
    
    # output
    User sub1 received notification from neetcode:A new video released
    User sub2 received notification from neetcode:A new video released
    User sub3 received notification from neetcode:A new video released
    > 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    5. Iterator

    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class ListNode:
        def __init__(self,val):
            self.val = val
            self.next = None
            
    class LinkedList:
        def __init__(self,head):
            self.head = head
            self.cur = None
        
        # Define Iterator
        def __iter__(self):
            self.cur = self.head
            return self
            
        # Iterate
        def __next__(self):
            if self.cur:
                val = self.cur.val
                self.cur = self.cur.next
                return val
            else:
                raise StopIteration
    
    # Initialize LinkedList
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    myList = LinkedList(head)
    
    
    # Iterate through LinkedList
    for n in myList:
        print(n)
        
    # output
    1
    2
    3
    > 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    6. Strategy

    Open-Closed Principle

    • Open-for extension
    • Closed-for modification

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    from abc import ABC, abstractmethod
    
    class FilterStrategy(ABC):
        
        @abstractmethod
        def removeValue(self,val):
            pass
        
    class RemoveNegativeStrategy(FilterStrategy):
        def removeValue(self,val):
            return val < 0
            
    class RemoveOddStrategy(FilterStrategy):
        def removeValue(self,val):
            return abs(val) % 2
            
    class Values:
        def __init__(self,vals):
            self.vals = vals
            
            def filter(self,strategy):
                res = []
                for n in self.vals:
                    if not strategy.removeValue(n):
                        res.append(n)
                return res
    
    values = Values([-7,-4,-1,0,2,6,9])
    
    print(values.filter(RemoveNegativeStrategy())) # [0,2,6,9]
    
    print(values.filter(RemoveOddStrategy())) # [-4,0,2,6]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    7. Adapter

    在这里插入图片描述

    在这里插入图片描述

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class UsbCable:
        def __init__(self):
            self.isPlugged = False
        
        def plugUsb(self):
            self.isPlugged = True
            
    class UsbPort:
        def __init__(self):
            self.portAvailable = True
        
        def plug(self,usb):
            if self.portAvailable:
                usb.plugUsb()
                self.portAvailable = False
        
    # UsbCables can plug directly into Usb ports
    usbCable = UsbCable()
    usbCable1 = UsbPort()
    UsbPort.plug(usbCable)
    
    class MicroUsbCable:
        def __init__(self):
            self.isPlugged = False
            
        def plugMicroUsb(self):
            self.isPlugged = True
            
    class MicroToUsbAdapter(UsbCable):
        def __init__(self,microUsbCable):
            self.microUsbCable = microUsbCable
            self.microUsbCable.plugMicroUsb()
            
            # can override UsbCable.plugUsb() if needed
    # MicroUsbCables can plug into Usb ports via an adapter
    microToUsbAdapter = MicroToUsbAdapter(MicroUsbCable())
    usbPort2 = UsbPort()
    usbPort2.plug(microToUsbAdapter)
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    8. Facade

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    # Online Python compiler (interpreter) to run Python online.
    # Write Python 3 code in this online editor and run it.
    class Array:
        def __init__(self):
            self.capacity = 2
            self.length = 0
            self.arr = [0] * 2  # Array of capacity = 2
            
        # Insert n in the last position of the array
        def pushback(self,n):
            if self.length == self.capacity:
                self.resize()
                
            # insert at next empty position
            self.arr[self.length] = n
            self.length += 1
            
        def resize(self):
            # Create new array of double capacity
            self.capacity = 2 * self.capacity
            newArr = [0] * self.capacity
            
            # Copy elements to newArr
            for i in range(self.length):
                
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 相关阅读:
    入门力扣自学笔记204 C++ (题目编号:1742)
    DCU集群搭建虚拟环境方法简介
    mysql 是不是要创建一个用户 然后给这个用户远程权限 操作msg数据库 而不是给root用户远程权限?
    【C语言】编译和链接
    合并两个非降数组
    optimizer和loss.backward()相关函数
    56.合并区间 | 1288.删除被覆盖的区间 | 986.区间列表的交集
    spring boot是如何加载Tomcat的
    Docker | 镜像浅析,以及制作自己的镜像
    12.函数
  • 原文地址:https://blog.csdn.net/qq_21381465/article/details/133802024