1. Singleton mode
Singleton pattern (Singleton Pattern) is a commonly used software design pattern, the main purpose of this pattern is to ensure that only one instance of a class exists. When you want to have only one instance of a class in the entire system, singleton objects can come in handy.
For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the content of the configuration file needs to be used in many places during the running of the program, that is to say, many instances of AppConfig objects need to be created, which results in the existence of multiple AppConfig instance objects in the system, which will seriously waste memory Resources, especially if the configuration file has a lot of content. In fact, for a class like AppConfig, we want only one instance object to exist during the running of the program. Note: Importing modules in python is a singleton mode.
Exercise: Create a Sun class
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Second, the factory model
Factory pattern is a design pattern used to create objects in software development.
When a "type" is input when the program is run, the corresponding object needs to be created here. This uses the factory model. In such a situation, the implementation code is based on the factory pattern, which can achieve scalable and maintainable code. When adding a new type, it is no longer necessary to modify the existing class, only adding subclasses that can generate a new type.
Use factory mode application scenario: You can use factory mode when you don’t know what kind of object the user wants to create.
example:
from: https://www.programmersought.com/article/66934024946/