More comprehensive single-case and factory models

concept
Factory mode: No matter how it is implemented, a factory mode can create a specific type of instance object by simply calling the interface of an abstract phone

Simple Factory Mode:
eg: An example gives a better understanding of the above:
We have a Person class that includes ways to get names and gender.There are two subclasses of males and female s to greet.There is also a factory class.
The factory class has a method name getPerson with two input parameters, name and gender.
The user uses the factory class by calling the getPerson method.

During the program, the user passes gender to the factory, which creates a gender-related object.So the factory class is at run time and determines which object should be created.

class Person:

def __init__(self):
    self.name = None
    self.gender = None

def getName(self):
    return self.name

def getGender(self):
    return self.gender

class Male(Person):

def __init__(self, name):
    print "Hello Mr." + name

class Female(Person):

def __init__(self, name):
    print "Hello Miss." + name

class Factory:

def getPerson(self, name, gender):
    if gender == 'M':
            return Male(name)
        if gender == 'F':
        return Female(name)

if name == '__main__':

factory = Factory()
person = factory.getPerson("Chetan", "M")


Abstract Factory Mode:
Provides an interface for creating a series of related or interdependent objects without specifying their specific classes.
class Burger():

"""
//Hamburger
"""
name=""
price=0.0
type='BURGER'
def getPrice(self):
    return self.price
def setPrice(self,price):
    self.price=price
def getName(self):
    return self.name

class CheeseBurger(Burger):

def __init__(self):
    self.name="cheese burger"
    self.price=10.0

class SpicyChickenBurger(Burger):

def __init__(self):
    self.name="spicy chicken burger"
    self.price=15.0

class Snack():

"""
//Snacks
"""
name = ""
price = 0.0
type = "SNACK"
def getPrice(self):
    return self.price
def setPrice(self, price):
    self.price = price
def getName(self):
    return self.name

class Chips(Snack):

def __init__(self):
    self.name = "chips"
    self.price = 6.0

class ChickenWings(Snack):

def __init__(self):
    self.name = "chicken wings"
    self.price = 12.0

class Beverage():

"""
//Drinks
"""
name = ""
price = 0.0
type = "BEVERAGE"
def getPrice(self):
    return self.price
def setPrice(self, price):
    self.price = price
def getName(self):
    return self.name

class Coke(Beverage):

def __init__(self):
    self.name = "coke"
    self.price = 4.0

class Milk(Beverage):

def __init__(self):
    self.name = "milk"
    self.price = 5.0

The above Burger, Snack, Beverage can all be considered products of this fast food restaurant. Since only abstract methods are provided, we call them abstract product classes, while cheese burger and other six subclasses derived from abstract product classes are called specific product classes.

class FoodFactory():

"""
The abstract factory foodFactory is an abstract factory class, while burgerFactory, snackFactory, beverageFactory are concrete factory classes.
"""
type=""
def createFood(self,foodClass):
    print(self.type," factory produce a instance.")
    foodIns=foodClass()
    return foodIns

class BurgerFactory(foodFactory):

def __init__(self):
    self.type="BURGER"

class SnackFactory(foodFactory):

def __init__(self):
    self.type="SNACK"

class BeverageFactory(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())

Factory Mode Advantages
The factory method is used to create the products the customer needs and hides from the customer the details of which specific product classes will be instantiated. This allows the factory to decide which product object to create independently. The details of how to create this object are completely encapsulated within the specific factory and when new products are added to the system, they conform to the open and close principle.
Disadvantages of factory mode
The number of classes in the system will increase in pairs, increasing the complexity of the system to some extent, bringing some extra overhead to the system, increasing the abstraction and understanding difficulty of the system
Factory Mode Suitable 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 the factory where the specific product object is created by the specific factory class). The abstract factory class specifies which object to create through its subclasses

Abstract Factory Mode:
Mode Advantages
Isolates the generation of specific classes so that the client does not need to know what is created When multiple objects in a product family are designed to work together, it ensures that it is convenient for the client to always add a new product family using only the objects in the same product family, without modifying the existing system, and conforms to the open-close principle
Mode drawbacks
Adding a new product hierarchy is cumbersome, requiring major modifications to the original system, or even modifications to the abstract layer code, which obviously causes greater inconvenience and violates the open-close principle
Model applicable environment
A system should not depend on the details of how product class instances are created, assembled, and expressed There are more than one family of products in the system, but products belonging to the same family of products will be used together each time only one family of products is used. This constraint must be reflected in the system design to ensure that the product hierarchy structure is stable and no new products will be added to the system after the design is completed.Product hierarchy or delete existing product hierarchy

Singleton mode
Singleton Pattern is a common software design pattern whose primary purpose is to ensure that only one instance of a class exists.A single object comes in handy when you want only one instance of a class to appear throughout the system.eg: printer in the system
Implementation:
Using modules:
In the mysingleton.py module file: (because the module generated a.pyc file the first time it was imported, it will be loaded directly from this next time, no regeneration is required)
class Singleton:(object):

 def foo(self):
   pass

singleton = Singeton()

Called in other files:
from mysingleton import singleton
Use decorators:
def Singleton(cls):

_instance = {}

def _singleton(*args, **kargs):

Here is the core code

    if cls not in _instance:
        _instance[cls] = cls(*args, **kargs)
    return _instance[cls]

Here is the core code

return _singleton

@Singleton
class A(object):

a = 1

def __init__(self, x=0):
    self.x = x

a1 = A(2)
a2 = A(3)
print(id(a1))
print(id(a2))

Using classes
import time
import threading
class Singleton(object):

_instance_lock = threading.Lock()

def __init__(self):
    time.sleep(1)

@classmethod
def instance(cls, *args, **kwargs):
    if not hasattr(Singleton, "_instance"):
        with Singleton._instance_lock:
            if not hasattr(Singleton, "_instance"):
                Singleton._instance = Singleton(*args, **kwargs)
    return Singleton._instance

def task(arg):

obj = Singleton.instance()
print(obj)

for i in range(10):

t = threading.Thread(target=task,args=[i,])
t.start()

time.sleep(20)
obj = Singleton.instance()
print(obj)

Consider multi-threading issues, lock to avoid running too fast, if there is IO operation in u init_, causing the creation of singletons to fail, the final optimization must be obj= Singleton.instance() to achieve singletons, if obj = Singleton() is not created singletons

Create a singleton based on u new_u method
import threading
class Singleton(object):

_instance_lock = threading.Lock()

def __init__(self):
    pass


def __new__(cls, *args, **kwargs):
    if not hasattr(Singleton, "_instance"):
        with Singleton._instance_lock:
            if not hasattr(Singleton, "_instance"):
                Singleton._instance = object.__new__(cls)  
    return Singleton._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)

def task(arg):

obj = Singleton()
print(obj)

for i in range(10):

t = threading.Thread(target=task,args=[i,])
t.start()

Implementation based on metaclass
import threading

class SingletonType(type):

_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
    if not hasattr(cls, "_instance"):
        with SingletonType._instance_lock:
            if not hasattr(cls, "_instance"):
                cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
    return cls._instance

class Foo(metaclass=SingletonType):

def __init__(self,name):
    self.name = name

obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)

Keywords: Python

Added by richie on Sun, 12 May 2019 11:07:20 +0300