An example of how to use the abstract factory mode in Python Design Mode Programming

Source: Internet
Author: User
This article mainly introduces the application of the abstract factory mode in Python Design Mode Programming. The example in this article shows some design optimization points of the abstract factory Mode Program. For more information, see Abstract Factory mode:Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
Advantages:Easy to switch between product series, as long as you change the corresponding factory.
Disadvantages:Creating a product is cumbersome and requires many additional and modifications.

Optimization 1:To avoid too many logic judgments on the client, a simple factory class can be encapsulated to generate product classes.
Optimization 2:To reduce the logical judgment in a simple factory class, the "reflection" mechanism can be used to read and retrieve the information of the product class based on the external configuration file.

# Encoding = UTF-8 ## by panda # Abstract Factory mode def printInfo (info): print unicode (info, 'utf-8 '). encode ('gbk') # Abstract product A: user table class IUser (): def Insert (self): pass def GetUser (self ): pass # sqlserver implemented User class SqlserverUser (IUser): def Insert (self): printInfo ("add a record to the User table in SQL Server") def GetUser (self ): printInfo ("get a record of the User table in SQL Server") # Access-implemented User class AccessUser (IUser): def Insert (self ): printInfo ("adding a record to the User table in Access") def GetUser (self): printInfo ("getting a User table in Access") # Abstract product B: department table class IDepartment (): def Insert (self): pass def GetUser (self): pass # Department class SqlserverDepartment (IUser): def Insert (self) implemented by sqlserver ): printInfo ("add a record to the Department table in SQL Server") def GetUser (self): printInfo ("get a record of the Department table in SQL Server ") # Department class AccessDepartment (IUser): def Insert (self): printInfo ("add a record to the Department table in Access") def GetUser (self ): printInfo ("getting a Department table record in Access") # Abstract Factory class ifacloud (): def CreateUser (self): pass def CreateDepartment (self ): pass # SQL server factory class SqlServerFactory (ifacloud): def CreateUser (self): return SqlserverUser () def CreateDepartment (self): return SqlserverDepartment () # access factory class AccessFactory (ifacloud ): def CreateUser (self): return AccessUser () def CreateDepartment (self): return AccessDepartment () # optimization 1: A simple factory class is used to encapsulate the logical judgment operation class DataAccess (): # db = "Sqlserver" db = "Access" @ staticmethod def CreateUser (): if (DataAccess. db = "Sqlserver"): return SqlserverUser () elif (DataAccess. db = "Access"): return AccessUser () @ staticmethod def CreateDepartment (): if (DataAccess. db = "Sqlserver"): return SqlserverDepartment () elif (DataAccess. db = "Access"): return AccessDepartment () # optimization 2: reflection mechanism, avoid using too many judgments # The following information can be obtained from the configuration file DBType = 'sqlserver '# 'access' DBTab_User = 'user' DBTab_Department = 'department' class DataAccessPro (): # db = "Sqlserver" db = "Access" @ staticmethod def CreateUser (): funName = DBType + DBTab_User return eval (funName )() # eval converts the string to the python expression @ staticmethod def CreateDepartment (): funName = DBType + DBTab_Department return eval (funName) () def clientUI (): printInfo ("\ n -------- Abstract factory method --------") factory = SqlServerFactory () iu = factory. createUser () iu. insert () iu. getUser () id = factory. createDepartment () id. insert () id. getUser () printInfo ("\ n -- Abstract Factory method + simple factory method --") iu = DataAccess. createUser () iu. insert () iu. getUser () id = DataAccess. createDepartment () id. insert () id. getUser () printInfo ("\ n-Abstract Factory method + simple factory method + reflection-") iu = DataAccessPro. createUser () iu. insert () iu. getUser () id = DataAccessPro. createDepartment () id. insert () id. getUser () return if _ name _ = '_ main _': clientUI ();

Class diagram:

The difference between the factory mode and the abstract factory mode: The factory mode defines a factory abstract interface in the derived class, and then the base class is responsible for creating specific objects. The Abstract Factory mode maintains a product family, the method by which the base class defines the product to be produced. The customer develops the product based on the interface of the derived class.

Instance:The example of a popular pizza shop can be moved out again. This time, based on the characteristics of the abstract factory model, we use different raw materials to make different flavors of pizza and create factories with different raw materials, different physical stores make different pizzas. Create an abstract type (PizzaIngredientFactory) of a product family (Dough, Sauce, Cheese, and Clam). The subclass of this type (NYPizzaIngredientFactory and ChicagoPizzaIngredientFactory) defines the method to produce the product.
Code:

#! /Usr/bin/python #-*-coding: UTF-8-*-import sysreload (sys) sys. setdefaultencoding ('utf-8') ''' class Pizza: name = "" dough = None sauce = None cheese = None clam = None def prepare (self ): pass def bake (self): print "bake for 25 minutes at 350. ". Decode ('utf-8') def cut (self): print" cut Into Diagonal slices. ". Decode ('utf-8') def box (self): print" is placed in the official box. ". Decode ('utf-8') def get_name (self): return self. name def set_name (self, name): self. name = name def to_string (self): string = "% s: \ n" % self. name string + = "dough: % s \ n" % self. dough. to_string () if self. dough else "" string + = "sauce: % s \ n" % self. sauce. to_string () if self. sauce else "" string + = "Cheese: % s \ n" % self. cheese. to_string () if self. cheese else "" string + = "clam: % s \ n" % self. clam. to_string () if self. clam else "" return string ''' what type of Pizza ''' class CheesePizza (Pizza): def _ init _ (self, ingredient_factory): self. ingredient_factory = ingredient_factory def prepare (self): print "preparation: % s" % self. name self. dough = self. ingredient_factory.create_dough () self. sauce = self. ingredient_factory.create_sauce () self. cheese = self. ingredient_factory.create_cheese () class ClamPizza (Pizza): def _ init _ (self, ingredient_factory): self. ingredient_factory = ingredient_factory def prepare (self): print "preparation: % s" % self. name self. dough = self. ingredient_factory.create_dough () self. sauce = self. ingredient_factory.create_sauce () self. clam = self. ingredient_factory.create_clam () '''pizza shop ''' class PizzaStore: def order_pizza (self, pizza_type): self. pizza = self. create_pizza (pizza_type) self. pizza. prepare () self. pizza. bake () self. pizza. cut () self. pizza. box () return self. pizza def create_pizza (self, pizza_type): pass '''new York pizza shop 1' class NYPizzaStore (PizzaStore): def create_pizza (self, pizza_type): ingredient_factory = workshop () if pizza_type = "cheese": pizza = CheesePizza (ingredient_factory) pizza. set_name ("New York style cheesecake ". decode ('utf-8') elif pizza_type = "clam": pizza = ClamPizza (ingredient_factory) pizza. set_name ("New York style clam pizza ". decode ('utf-8') else: pizza = None return pizza' '''chicago pizza shop 2' class ChicagoPizzaStore (PizzaStore): def create_pizza (self, pizza_type ): ingredient_factory = ChicagoPizzaIngredientFactory () if pizza_type = "cheese": pizza = CheesePizza (ingredient_factory) pizza. set_name ("Chicago-style cheesecake ". decode ('utf-8') elif pizza_type = "clam": pizza = ClamPizza (ingredient_factory) pizza. set_name ("Chicago style clam pizza ". decode ('utf-8') else: pizza = None return pizza' '''factory for producing pizzas ''' class PizzaIngredientFactory: def create_dough (self ): pass def create_sauce (self): pass def create_cheese (self): pass def create_clam (self): pass ''' entity factory for producing pizza 1' class NYPizzaIngredientFactory (PizzaIngredientFactory ): def create_dough (self): return ThinDough () def create_sauce (self): return MarinaraSauce () def create_cheese (self): return FreshCheese () def create_clam (self): return FreshClam () '''entity factory 2 ''' class ChicagoPizzaIngredientFactory (PizzaIngredientFactory): def create_dough (self): return ThickDough () def create_sauce (self): return MushroomSauce () def create_cheese (self): return BlueCheese () def create_clam (self): return FrozenClam () class Dough: def to_string (self): pass class ThinDough (Dough ): def to_string (self): return "thin Dough" class ThickDough (Dough): def to_string (self): return "thick Dough" class Sauce: def to_string (self ): pass class MarinaraSauce (Sauce): def to_string (self): return "ketchup" class MushroomSauce (Sauce): def to_string (self): return "mushroom Sauce" class Cheese: def to_string (self): pass class FreshCheese (Cheese): def to_string (self): return "fresh Cheese" class BlueCheese (Cheese): def to_string (self ): return "blue cheese" class Clam: def to_string (self): pass class FreshClam (Clam): def to_string (self): return "fresh Clam" class FrozenClam (Clam ): def to_string (self): return "Frozen clam" if _ name _ = "_ main _": # create two pizza stores ny_store = NYPizzaStore () chicago _store = ChicagoPizzaStore () # order a cheese-style pizza = ny_store.order_pizza ("cheese") print pizza from the first pizza object. to_string () print "Mike ordered a % s" % pizza. get_name () print pizza = chicag_store.order_pizza ("clam") print pizza. to_string () print "John ordered a % s" % pizza. get_name ()

Result:

Preparation: New York style cheesecake is baked for 25 minutes at 350. Cut into diagonal slices. In the official box. New York style cheesecake: dough: thin dough sauce: tomato sauce cheese: fresh cheese Mike ordered a New York style cheesecake preparation: Chicago style cheesecake baked for 25 minutes at 350. Cut into diagonal slices. In the official box. Chicago style clam pizza: dough: thick dough sauce: mushroom sauce clam: Frozen clam John ordered a Chicago style clam pizza

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: info-contact@alibabacloud.com 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.