Factory Pattern of Design Patterns

1. Before talking about the factory pattern, implement an interface through two methods

#Two methods implemented by the interface 
class Payment:
     def pay(self,money):
         #Throw an exception when the subclass calls the pay method. If the subclass calls this method, it must implement this method first. 
        raise NotImplementedError
 class Alipay(Payment) :
     def pay(self,money):
         print ( ' Use Ali to pay %s ' % money)

from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):
    @abstractmethod
    def pay(self,money): #implemented
         by the method provided by the system If the subclass calls this method, it must implement this method before calling 
        pass 
class Alipay(Payment):
     def pay(self,money):
         print ( ' Use Ali paid %s ' %money)

2. Implementation of the Factory Pattern

from abc import abstractmethod,ABCMeta
 class Payment(metaclass= ABCMeta): #Interface 
  class, providing payment methods @abstractmethod
def pay(self,money): raise NotImplementedError class Alipayment(Payment): #To
  implement the interface class, the pay method of the interface must be implemented
def pay(self,money): print ( ' Ali paid %s yuan ' % money) class Applepayment (Payment): def pay(self,money): print ( ' Apple paid %s yuan ' % money) class Wechatpaymet(Payment): def pay(self,money): print ( ' Wechat paid %s yuan ' % money) classFactory: #Factory class, hiding the details of object creation @classmethod def create_payment(self,args): if args == ' ali ' : return Alipayment() elif args == ' apple ' : return Applepayment() elif args == ' wechat ' : return Wechatpaymet() else : raise NameError(args) payment = Factory.create_payment('ali') payment.pay(50)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169038&siteId=291194637