In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Xiaobian to share with you how to use python factory method mode, I hope you have something to gain after reading this article, let's discuss it together!
I. Introduction
The factory pattern is a creation pattern that provides the best way to create objects.
In the factory pattern, we create objects without exposing the implementation logic to clients, but instead point to newly created objects through a common interface class.
II. Main roles of the factory approach pattern
Abstract Factory: Provides an interface for creating products through which callers access the factory method newProduct() of a concrete factory to create products.
ConcreteFactory: Mainly implements abstract methods in abstract factories to complete the creation of concrete products.
Abstract Product: defines the specification of the product, describes the main features and functions of the product.
ConcreteProduct: The interface defined by abstract product is implemented, created by concrete factory, and it corresponds to concrete factory one by one.
III. Simple factory model
Content: The details of the object creation implementation are not exposed directly to the client, but rather the factory class is responsible for creating instances of the product class.
Specific code (jiandan.py):
from abc import ABCMeta, abstractmethod class Payment(metaclass=ABCMeta): @abstractmethod def pay(self): pass class WechatPay(Payment): def pay(self, money): print("Weixin Pay %s" % money) return class Alipay(Payment): def __init__(self, huabei=False): self.huabei = huabei def pay(self, money): if self.huabei: print("spend %s" % money) else: print("Alipay balance payment %s" % money) class PaymentFactory: def create_pay(self, method): if method == "wechat": return WechatPay() elif method == "alipay": return Alipay() elif method == "huabei": return Alipay(huabei=True) else: raise TypeError("No such payment name %s" % method) # clientpf = PaymentFactory()p = pf.create_pay("huabei")p.pay(100)
Results:
ABCMeta is a Python metaclass used to create abstract base classes in Python programs, abstract methods declared in abstract base classes, decorated with abstractmethod decorators.
Simply put: create a public abstract class, and then create multiple payment classes to inherit this abstract class, various payment classes to implement specific payment methods, through the factory class to select payment methods, so that the customer service only implements payment methods, do not need to know the specific implementation method.
Advantages:
Hide implementation details of object creation Client does not need to modify code
Disadvantages:
Violates the principle of single responsibility, centralizing the creation logic into a factory class. When adding new products, you need to modify the factory class code. Violates the principle of opening and closing.
IV. Factory model
Content: Defines an interface (factory class) for creating objects, letting the factory subclass decide which product class to instantiate.
Specific code (factory_method.py):
from abc import ABCMeta, abstractmethod class Payment(metaclass=ABCMeta): @abstractmethod def pay(self): pass class WechatPay(Payment): def pay(self, money): print("Weixin Pay %s" % money) return class Alipay(Payment): def __init__(self, huabei=False): self.huabei = huabei def pay(self, money): if self.huabei: print("spend %s" % money) else: print(" %s" % money) class PaymentFactory(metaclass=ABCMeta): @abstractmethod def create_method(self): pass class AlipayFactory(PaymentFactory): def create_method(self): return Alipay() class WechatFactory(PaymentFactory): def create_method(self): return WechatPay() class HuabeiFactory(PaymentFactory): def create_method(self): return Alipay(huabei=True) pf = HuabeiFactory()p = pf.create_method()p.pay(100)
Results:
Abstract factory pattern
Content: Defines a factory class interface that lets factory subclasses create a set of related or interdependent objects.
In contrast to the factory pattern, each product in the abstract factory pattern produces a set of products.
Specific code (abstract_factory.py):
from abc import ABCMeta, abstractmethod"" abstract product "" class PhoneShell(metaclass=ABCMeta): @abstractmethod def show_shell(self): pass class OS(metaclass=ABCMeta): @abstractmethod def show_os(self): pass class CPU(metaclass=ABCMeta): @abstractmethod def show_cpu(self): pass #abstract factory class PhoneFactory(metaclass=ABCMeta): @abstractmethod def make_shell(self): pass @abstractmethod def make_cpu(self): pass @abstractmethod def make_os(self): pass #Specific product class SmallShell(PhoneShell): def show_shell(self): print("Normal phone case Small phone case") class BigShell(PhoneShell): def show_shell(self): print("Normal phone case Large phone case") class AppleShell(PhoneShell): def show_shell(self): print("Apple phone case") class SnapDragonCPU(CPU): def show_cpu(self): print("Snapdragon CPU") class MediaTekCPU(CPU): def show_cpu(self): print("MediaTek CPU") class AppleCPU(CPU): def show_cpu(self): print("Apple CPU") class AppleOS(OS): def show_os(self): print("Apple OS") class AndroidOS(OS): def show_os(self): print("Android System") class IOS(OS): def show_os(self): print("IOS System") #Specific Factory class MiFactory(PhoneFactory): def make_cpu(self): return SnapDragonCPU() def make_os(self): return AndroidOS() def make_shell(self): return BigShell() class HuaweiFactory(PhoneFactory): def make_cpu(self): return MediaTekCPU() def make_os(self): return AndroidOS() def make_shell(self): return SmallShell() class IPhoneFactory(PhoneFactory): def make_cpu(self): return AppleCPU() def make_os(self): return AppleOS() def make_shell(self): return AppleShell() class Phone: def __init__(self, cpu, os, shell): self.cpu = cpu self.os = os self.shell = shell def show_info(self): print("Phone info:") self.cpu.show_cpu() self.os.show_os() self.shell.show_shell() def make_phone(factory): cpu = factory.make_cpu() os = factory.make_os() shell = factory.make_shell() return Phone(cpu, os, shell) p1 = make_phone(MiFactory())p1.show_info()
Results:
Advantages:
Separating the client from the concrete implementation of the class creates a complete product family for each factory, making it easy to exchange product families for consistency (and constraints between products)
Disadvantages:
Difficult to support new kinds of abstract products
After reading this article, I believe you have a certain understanding of "how to use python factory method mode". If you want to know more about it, please pay attention to the industry information channel. Thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.