python-Factory Method mode

Source: Internet
Author: User

Lack of a simple factory model:

In the simple factory model, only one factory class is provided, which is at the center of the instantiation of the product class, knowing the details of the creation of each product object and deciding when to instantiate which product class. The biggest drawback of the simple factory model is that when a new product is added to the system, the factory class must be modified to incorporate the necessary processing logic, which violates the "open and closed principle". In the simple factory model, all the products are created by the same factory, the factory class responsibilities are heavier, the business logic is more complex, the specific product and factory class coupling between the high, seriously affect the flexibility and scalability of the system, and the factory method model can be a good solution to this problem.

Description: Factory method Mode:

Defines an interface for creating objects, but lets subclasses decide which class to instantiate. The factory method pattern defers the instantiation of a class to its subclasses.

The factory method pattern is the further extraction of the simple factory pattern. Due to object-oriented polymorphism, the factory method pattern keeps a simple factory and overcomes his shortcomings at the same time. In the factory method pattern, the core factory is promoted to an abstract class, and the concrete creation is given to his subclasses. This abstract factory class only specifies the interface that the specific factory implements, and does not explicitly indicate how to instantiate a product class, which allows the factory method model to allow the system to easily introduce new products without modifying the original product structure.

Abstract Factory mode:

Provides an interface to create a series of related or interdependent objects without specifying their specific classes.

Abstract Factory mode is one of the most abstract and general forms of all forms of Factory mode. Abstract Factory mode can be used when the specific product produced by the system is not a simple object, but a number of specific products in different product hierarchy, belonging to different types, and the specific factory in the abstract factory model does not just create a product, it is responsible for creating a family of products Abstract Factory mode is simpler and more efficient than factory method mode when a factory hierarchy can create all objects in a product family that belong to different product hierarchy structures

The abstract factory pattern consists of the following 4 roles: Abstractfactory (abstract Factory) Concretefactory (concrete Factory) Abstractproduct (abstract product) concreteproduct (Specific products)


Ordering system for a snack table. On a large touchscreen display, there are three types of dishes to choose from: main meals, snacks, and drinks from Hamburg. When we choose the food we need, the payment is completed and the order is generated.

classBurger ():"""Hamburg"""name="" Price=0.0type='BURGER'    defGetPrice (self):returnSelf.pricedefSetprice (self,price): Self.price= PricedefGetName (self):returnSelf.nameclassCheeseburger (Burger):def __init__(self):"Cheese Burger"Self.price=10.0classSpicychickenburger (Burger):def __init__(self):"Spicy Chicken Burger"Self.price=15.0classSnack ():"""Small Food category"""name="" Price= 0.0type="SNACK"    defGetPrice (self):returnSelf.pricedefSetprice (Self, Price): Self.price= PricedefGetName (self):returnSelf.nameclassChips (Snack):def __init__(self):"Chips"Self.price= 6.0classchickenwings (Snack):def __init__(self):"Chicken Wings"Self.price= 12.0classBeverage ():"""Beverages"""name="" Price= 0.0type="Beverage"    defGetPrice (self):returnSelf.pricedefSetprice (Self, Price): Self.price= PricedefGetName (self):returnSelf.nameclassCoke (beverage):def __init__(self):"Coke"Self.price= 4.0classMilk (beverage):def __init__(self):"Milk"Self.price= 5.0# above the Burger,snack,beverage, can be regarded as the product of the fast food restaurant, because only provides an abstract method, we call them abstract product class, and Cheese burger and other 6 by the abstract product class derived from the subclass, called the specific product class.
classfoodfactory ():"""Abstract Factory Foodfactory are abstract factory classes, while burgerfactory,snackfactory,beveragefactory are specific factory classes. """type="" defCreatefood (self,foodclass):Print(Self.type,"factory produce a instance.") Foodins=Foodclass ()returnFoodinsclassburgerfactory (foodfactory):def __init__(self): Self.type="BURGER"classsnackfactory (foodfactory):def __init__(self): Self.type="SNACK"classBeverageFactory (foodfactory):def __init__(self): Self.type="Beverage"if __name__=="__main__": Burger_factory=burgerfactory () snack_factory=snackfactory () beverage_factory=beveragefactory () Cheese_burger=Burger_factory.createfood (Cheeseburger)Print(Cheese_burger.getname (), Cheese_burger.getprice ()) Chicken_wings=Snack_factory.createfood (chickenwings)Print(Chicken_wings.getname (), Chicken_wings.getprice ()) Coke_drink=Beverage_factory.createfood (Coke)Print(Coke_drink.getname (), Coke_drink.getprice ())

Printing results:

BURGER factory produce a instance.
Cheese Burger 10.0
SNACK factory produce a instance.
Chicken Wings 12.0
Beverage factory produce a instance.
Coke 4.0

In the example, there are three concrete factory burgerfactory,snackfactory,beveragefactory in the abstract factory, three factories correspond respectively, in other words, the production of three kinds of products burger,snack,beverage.

Factory Method Mode Advantages

The factory method is used to create the products required by the customer, while also hiding to the customer which specific product class will be instantiated this detail will allow the factory to determine what product object is created, and how to create the details of this object completely encapsulated in the specific factory in the system to add new products, fully comply with the open and closed principle

Pattern disadvantage

The number of classes in the system increases in pairs, increasing the complexity of the system to a certain extent, bringing some additional overhead to the system, which increases the abstraction and difficulty of comprehension of the system.

Mode applicable environment

The client does not know the class of the object it needs (the client does not need to know the class name of the specific product class, just need to know the corresponding factory, the specific product object is created by the specific factory Class) abstract factory class through its subclasses to specify which object to create

Abstract Factory mode: pattern advantages

Isolate the build of a specific class so that the client does not need to know what is being created when multiple objects in a product family are designed to work together, it ensures that the client always uses only objects from the same product family to add a new product family easily, without modifying the existing system, in line with the opening and shutting principle

Pattern disadvantage

Add new product grade structure trouble, need to make large changes to the original system, and even need to modify the abstraction layer code, which will obviously bring greater inconvenience, contrary to the opening and closing principle

Mode applicable environment

A system should not depend on how a product class instance is created, composed, and expressed in a detail system with more than one product family, but each time only one product family belonging to the same product family will be used together, this constraint must be reflected in the system design of the product hierarchy structure is stable, after the design is completed, Do not add new product hierarchies to the system or delete existing product hierarchies

python-Factory Method mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.