Home Backend Development Python Tutorial How to use object-oriented design patterns in Python

How to use object-oriented design patterns in Python

Oct 22, 2023 am 08:22 AM
python Design Patterns object-oriented

How to use object-oriented design patterns in Python

How to use the object-oriented design pattern in Python requires specific code examples

Overview:
In Python programming, the object-oriented design pattern is very important a concept. It provides a structured approach to problem solving and makes code easier to understand, maintain, and extend. This article will introduce several common object-oriented design patterns and provide specific code examples to help readers better understand and apply these patterns.

1. Singleton Pattern:
The singleton pattern is a design pattern that can only create one instance. It is suitable for situations where global uniqueness needs to be guaranteed and is frequently accessed by multiple modules or objects. The following is a simple example of the singleton pattern:

class Singleton:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance
Copy after login

In the above code, the singleton pattern is implemented by overriding the __new__ method. __new__The method is called before the instance is created and can control the instance creation process. By determining whether the __instance attribute exists, you can ensure that only one instance is created.

Sample code using singleton mode:

a = Singleton()
b = Singleton()
print(a is b)  # True
Copy after login

In the above example, a and b are both instances created through the Singleton class. Because the Singleton class is a singleton mode, a and b are same instance.

2. Factory Pattern:
Factory Pattern is a design pattern that creates different types of objects based on different inputs. It is suitable for situations where different objects need to be created based on different parameters. The following is a simple factory pattern example:

class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("Draw a circle")

class Square(Shape):
    def draw(self):
        print("Draw a square")

class ShapeFactory:
    def create_shape(self, shape_type):
        if shape_type == "circle":
            return Circle()
        elif shape_type == "square":
            return Square()
        else:
            raise ValueError("Invalid shape type")
Copy after login

In the above code, the Shape class is an abstract class and defines an abstract method draw. The Circle and Square classes inherit from the Shape class respectively and implement the draw method. The ShapeFactory class is a factory class responsible for creating corresponding objects based on input parameters.

Sample code using factory mode:

factory = ShapeFactory()
circle = factory.create_shape("circle")
circle.draw()  # Draw a circle

square = factory.create_shape("square")
square.draw()  # Draw a square
Copy after login

In the above example, different objects are created according to different parameters through the ShapeFactory class. According to different shape_type parameters, the create_shape method returns the corresponding object, and then calls the draw method.

3. Observer Pattern:
The Observer Pattern is a one-to-many dependency relationship between objects. When the state of one object changes, it will automatically notify those who depend on it. object. The following is a simple example of the observer pattern:

class Subject:
    def __init__(self):
        self.observers = []

    def add_observer(self, observer):
        self.observers.append(observer)

    def remove_observer(self, observer):
        self.observers.remove(observer)

    def notify_observers(self):
        for observer in self.observers:
            observer.update()

class Observer:
    def update(self):
        pass

class ConcreteObserver(Observer):
    def update(self):
        print("Received update from subject")

subject = Subject()
observer = ConcreteObserver()

subject.add_observer(observer)
subject.notify_observers()  # Received update from subject

subject.remove_observer(observer)
subject.notify_observers()  # 无输出,因为观察者已被移除
Copy after login

In the above code, the Subject class is the observer and defines methods for adding, removing and notifying observers. The Observer class is an abstract class of observers and defines an abstract method update. The ConcreteObserver class is a concrete observer, inherits from the Observer class and implements the update method.

Sample code using the observer pattern:

subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()

subject.add_observer(observer1)
subject.add_observer(observer2)

subject.notify_observers()  # 两个观察者都收到了更新通知
Copy after login

In the above example, the subject object adds two observers (observer1 and observer2). When the subject object calls the notify_observers method, the two observations Everyone will receive an update notification.

Summary:
This article introduces several common object-oriented design patterns and provides specific code examples. By using these design patterns, you can make your code easier to understand, maintain, and extend. I hope readers can better understand and apply object-oriented design patterns through the introduction and sample code of this article.

The above is the detailed content of How to use object-oriented design patterns in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles