This is the 29th day of my participation in Gwen Challenge
1. An overview of the
We often hear people say, what design pattern do you use for this code?
Hey, what is the design pattern, don’t understand what the big guy is saying (laughing and crying. JPG), quickly learn it
Design patterns are typical solutions to common software design problems. They are like prefabricated blueprints that can be adapted to meet requirements and can be used to solve recurring design problems in your code
Design patterns are not used in the same way as methods or libraries, and it is difficult to directly apply a design pattern to your own programs. A pattern is not a specific piece of code, but a general idea to solve a specific problem. You can follow the pattern to implement a solution that fits the actual needs of your application.
Design pattern is for the object oriented language holds the content, is when we are faced with a class of problems fixed practice, there are many design patterns, the more popular is :(group of four)GOF23 design patterns.
Object orientation (OOP) is a paradigm in which the idea is to encapsulate blocks of data and data-related behavior in code into special entities called objects, which are generated based on a series of “blueprints” given by programmers, called classes. In terms of object-oriented features, there are three major features (encapsulation, inheritance, polymorphism).
Why use design patterns?
Excellent design patterns can improve the quality of our code, mainly in three aspects:
- Code reuse, improve development efficiency, reduce development costs of one of the most common ways
- Strong expansibility, able to develop new functions or requirements on the basis of the original code, quickly online
- Convenient maintenance, good frame maintenance, can reduce the input of personnel
So, for starters, we study the two most common patterns: factory and singleton
In this issue, we also learn and simulate from two of the most commonly used patterns.
2. Factory mode
Factory pattern is a kind of creative design pattern, which realizes the separation of creator and caller, and uses a special factory type to select implementation classes and create objects for unified management and control.
The factory pattern takes the approach of providing a method to create an object in a parent class, allowing subclasses to decide which model to instantiate the object.
The factory pattern structure is as follows:
Factory mode applies to the following scenarios:
-
Users can extend the internal components of the software library or framework
-
The exact class of objects and their dependencies cannot be predicted
-
Reuse existing objects to save system resources instead of recreating objects every time
Let’s implement a simple factory model DEMO, producing cars.
Class CarFactory: def createcar(self,brand): return BENCI() elif brand == "BMW ": return Baoma() else: return BYD() class Baoma: pass class BENCI: pass class BYD: Pass factory = CarFactory() car1 = factory.createcar("BYD") car2 = factory.createcar(" BMW ") print(" car1 ": ",car1) print(" print ", Car2)Copy the code
Advantages of the factory model:
- Tight coupling between creators and specific products can be avoided.
- Single responsibility principle. Product creation code can be placed in a single location in your program, making it easier to maintain.
- Open and close principle. You can introduce new product types into your program without having to change existing client code.
Disadvantages of the factory model:
Applying the factory method pattern requires the introduction of many new subclasses, which can make the code more complex. The best case scenario is to introduce this pattern into an existing hierarchy of creator classes.
3. Singleton mode
The core role of the Singleton Pattern is to ensure that there is only one instance of a class and to provide a global access point to that instance.
Singleton pattern structure
- When an object is created, it checks whether it exists and returns the object if it does. If not, create a new object
The singleton mode applies to the following scenarios:
- The program creates only one available instance for all clients
- Global variables need to be more tightly controlled
Let’s do a little DEMO in singleton mode
__init_flag = True def __new__(CLS, *args, **kwargs): class MySinglection: __obj = None if cls.__obj == None: cls.__obj = object.__new__(cls) return cls.__obj def __init__(self,name): if MySinglection.__init_flag: print ("Init....." My2 = MySinglection("aaa") my2 = MySinglection("BB") print Print ("my2 ", "my2 ")Copy the code
Advantages of singleton mode
- The singleton pattern generates only one instance object, reducing the overhead of system resources. When the generation of an object requires a lot of resources, such as reading configuration files or generating other dependent objects, a singleton can be generated and stored permanently in memory, thus greatly reducing the overhead.
- A global access node pointing to the instance is obtained.
- A singleton is initialized only when it is first requested
Disadvantages of the singleton pattern
- Violation of the single responsibility principle
- The singleton pattern can mask bad design, such as too much knowledge between the components of a program.
- This mode requires special processing in multi-threaded environment to avoid multiple threads creating singleton objects.
- Singleton client-side code unit testing can be difficult because many testing frameworks create mock objects in an inheritance-based manner.
conclusion
In this installment, we will learn and understand the basic concepts of design patterns. We will use Python to implement the factory pattern and singleton pattern that we often use. In our work, according to the needs of the implementation scenario, we will play an important role in designing our code in advance.
To this end, we learn how to master the design model with the capacity, but also for our ability to bring significant results.
Ok, this is the content of this issue, welcome to leave a comment in the comment section, like attention, see you next time ~