Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Creative Factory pattern in Python Design pattern

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use the creative factory pattern in the Python design pattern, which is very detailed and has a certain reference value. Interested friends must read it!

First, factory mode (Factory Pattern)

The factory pattern (Factory Pattern) provides the best way to instantiate (create) objects.

In the factory pattern, an abstract factory class (class Factory) is defined first, and a general Interface (interface) function is defined in the factory class for instantiating objects. Then when Client wants to instantiate the object of a specific class, it just needs to tell the factory class the requirement, which instantiates the object on demand and returns it. As a caller, Client does not need to know any details of object instantiation, which means that any Client does not need to consider adjusting its own code according to the instantiation details of the object.

For example, when we need to buy a batch of computers, as long as we tell the computer factory our needs, the computer factory will help us to do the computers well, instead of having to do the computers ourselves. We don't have to know how the computer is made. This is the factory model.

The advantage of the factory pattern is to help us extract the instantiated part of the object in order to reduce the code coupling in the system and enhance the expansibility of the system. It is a practice of decoupling thought.

Second, application scenarios

Multi-Drivers (Multi-driver Architecture)

Coding example 1. Simple factory mode

The simple factory pattern simply encapsulates the instantiation of different objects into a single factory class.

When we need to instantiate an object, we simply tell our requirements to the simple factory class, and then the simple factory class creates the corresponding object according to our requirements. Suitable for simple business scenarios.

Advantages: the simple factory pattern can dynamically generate the objects of the classes needed by the users according to the requirements, and the users do not have to know how to create the objects, which makes each module perform its own duties and reduces the coupling of the system.

Disadvantages: poor scalability, in violation of the opening and closing principle (which means that software implementations should be open to extensions and closed to modifications). When you add a new product, you need to modify the code of the simple factory class.

Entity roles:

Abstract category of product

Specific product subcategory

Simple factory class

Import abc# product abstract class class Productor (metaclass=abc.ABCMeta): @ abc.abstractmethod def product (self, car): pass # A more specific product class, which is a subclass of the product abstract class class Xiaomi (Productor): "" Xiaomi phone "" def product (self, price): return f "to make a Xiaomi phone Price {price} yuan "def _ repr__ (self): return f" Xiaomi, {id (self)} "# A more specific product category is a subclass of the product abstract class class Huawei (Productor):"Huawei Mobile phone"def product (self, price): return f" to make a Huawei mobile phone Price {price} yuan "def _ _ repr__ (self): return f" Huawei {id (self)} "# simple factory class class PhoneBrandFactory:"simple factory"def create_productor (self, brand): if brand = =" Xiaomi ": return Xiaomi () if brand = =" Huawei ": return Huawei () else: raise TypeError (f" there is no mobile phone manufacturer named {brand}. ") If _ _ name__ = = "_ main__": # get the object of a specific product class Xiaomi = PhoneBrandFactory (). Create_productor ("Xiaomi") Huawei = PhoneBrandFactory (). Create_productor ("Huawei") print (Xiaomi) print (Huawei) print (Xiaomi.product (2999)) print (Huawei.product (5999)) 2, factory method mode

In the factory method pattern, the factory class derives any subfactory class, and each subfactory class corresponds to a specific product class, then the instantiation of the object of a product class is handed over to this subfactory class.

The factory method pattern is an improvement of the simple factory pattern. When we need to extend a new product, we only need to extend a new subfactory class without modifying the original code of the factory class, which is in line with the opening and closing principle.

Advantages: good expansibility, in line with the opening and closing principle. When adding a new product, you only need to add the corresponding product category and the corresponding factory subcategory. At the same time, it also makes each product category and the corresponding factory subcategory in line with the principle of single responsibility, each factory is responsible for only one product, rather than one factory to generate all goods.

Disadvantages: when we add new products, we also need to provide corresponding factory classes, the number of classes in the system will increase exponentially, which is equivalent to increasing the complexity of the system.

Entity roles:

Abstract category of product

Specific product subcategory

Factory class

Specific factory subclass

Import abc# product abstract class class Productor (metaclass=abc.ABCMeta): @ abc.abstractmethod def product (self, car): pass # A more specific product class, which is a subclass of the product abstract class class Xiaomi (Productor): "" Xiaomi phone "" def product (self, price): return f "to make a Xiaomi phone Price {price} yuan "def _ repr__ (self): return f" Xiaomi, {id (self)} "# A more specific product category is a subclass of the product abstract class class Huawei (Productor):"Huawei Mobile phone"def product (self, price): return f" to make a Huawei mobile phone Price {price} yuan "def _ _ repr__ (self): return f" Huawei {id (self)} "# Factory class class PhoneBrandFactory (metaclass=abc.ABCMeta):"Abstract Factory" @ abc.abstractmethod def create_productor (self) Brand): pass # subfactory class class XiaomiFactory (PhoneBrandFactory): def create_productor (self): return Xiaomi () # subfactory class corresponding to specific product class HuaweiFactory (PhoneBrandFactory): def create_productor (self): return Huawei () if _ _ name__ = = "_ main__": # A corresponding subfactory class is completed by this subfactory class Instantiate the object of the product class Xiaomi = XiaomiFactory (). Create_productor () Huawei = HuaweiFactory (). Create_productor () print (Xiaomi) print (Huawei) print (Xiaomi.product (2999)) print (Huawei.product (5999)) 3. Abstract factory pattern

Abstract factory pattern is also an improvement of factory method pattern. The factory method model deals with the production of the same type of computers of different brands, while the abstract factory model deals with the production of multiple types of computers of different brands.

For example, the factory method model of the computer factory can only produce old-fashioned desktop computers, but if you now need to produce desktops, laptops, tablets and other types of computers, then the factory method mode is not very convenient. The abstract factory model can solve the problem that computer factories produce multiple types of computers, that is, to solve the problem of one factory producing multiple types of products.

If we need desktops and laptops, when we want multiple products, the factory method pattern can not meet our needs; while the abstract method pattern, in advance in the abstract factory, defines a variety of products that may be needed. for example, desktops, laptops, tablets, etc., when there is a need, we only need to create relevant subclasses and related subfactory classes.

Advantages: abstract factory classes create multiple types of products, and when required, you can create related sub-product classes and sub-factory classes to obtain. That is, it can satisfy the production of different types of computers of different brands.

Disadvantages: it is difficult to expand new types of products. Abstract factory pattern requires us to identify the types of products that may be needed in advance in the factory abstract class to meet the needs of multiple products of different brands. But if the type of product we need is not determined in advance in the factory abstract class, then we need to modify the factory abstract class, and once the factory abstract class is modified, then all factory subclasses also need to be modified. this is obviously not convenient to extend.

Entity roles:

Product functional feature abstract class

Specific product functional feature subcategory

Abstract category of product

Specific product subcategory

Abstract factory class

Import abc# product functional feature abstract class class PhoneShell (metaclass=abc.ABCMeta): @ abc.abstractmethod def shell (self): pass class Cpu (metaclass=abc.ABCMeta): @ abc.abstractmethod def cpu (self): pass class OS (metaclass=abc.ABCMeta): @ abc.abstractmethod def system (self): pass # specific product functional feature class class SmallShell (PhoneShell): @ property def Shell (self): return "small screen" class BigShell (PhoneShell): @ property def shell (self): return "big screen" class SnapDragonCpu (Cpu): @ property def cpu (self): return "Snapdragon cpu" class AppleCpu (Cpu): @ property def cpu (self): return "Apple cpu" class Android (OS): @ property def system ( Self): return "Android" class IOS (OS): @ property def system (self): return "IOS" # abstract class class ProductPhone: def _ _ init__ (self Factory): self.factory = factory () def product (self): self.shell = self.factory.product_shell () self.cpu = self.factory.product_cpu () self.OS = self.factory.product_system () def show_info (self): print (f "{self.factory}", f "configuration Information: {self.shell.shell}, {self.cpu.cpu} {self.OS.system} ") # specific product subcategory class XiaomiFactory (PhoneFactory): def product_shell (self): return BigShell () def product_cpu (self): return SnapDragonCpu () def product_system (self): return Android () def _ _ repr__ (self): return" Xiaomi phone " The price is 2999! " Class IphoneFactory (PhoneFactory): def product_shell (self): return SmallShell () def product_cpu (self): return AppleCpu () def product_system (self): return IOS () def _ _ repr__ (self): return "iPhone, price 8999!" # abstract factory class class PhoneFactory (metaclass=abc.ABCMeta): @ abc.abstractmethod def product_shell (self): pass @ abc.abstractmethod def product_cpu (self): pass @ abc.abstractmethod def product_system (self): pass if _ _ name__ = = "_ _ main__": xiaomi = ProductPhone (XiaomiFactory) xiaomi.product () xiaomi.show_info () iphone = ProductPhone (IphoneFactory) iphone.product () iphone.show_info () these are all the contents of the article "how to use the Creative Factory pattern in the Python Design pattern" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report