This article mainly introduces the python design mode and implements various common Python design modes through simple code, including the bridge mode, Observer Mode, Adapter mode, Factory mode, and Singleton mode, for more information about the common python design patterns, see the examples in this article. We will share this with you for your reference. The details are as follows:
##! /Usr/bin/env python ###-*-coding: UTF-8 ## class HttpBase: # def get (self): # psss # class Http1 (HttpBase ): # def get (self): # print 'http1' # class Http2 (HttpBase): # def get (self): # print 'http2' ### class Base: # def _ init _ (self): # self. httpobj = None # def http (self): # self. httpobj. get () # def compute (self): # self. http () # self. show () ## virtual function # def show (self): # pass # def using Y (self, k): # print 'using Y', k #### bridge mode, associate different http1 and http2 # class BaseA (Base): # def _ init _ (self): # self. httpobj = Http1 () # def every Y (self, k): # print 'a every Y', k # def show (self ): # print 'show a' # class BaseB (Base): # def _ init _ (self): # self. httpobj = Http2 () # def every Y (self, k): # print 'B every Y', k # def show (self ): # print 'show B '### Observer Mode # class Observer: # def _ init _ (self): # self. listOB = [] # def register (self, obj): # self. listOB. append (obj) # def every Y (self): # for obj in self. listOB: # obj. every Y (len (self. listOB) ### Adapter mode # class B1: # def http (self): # BaseB (). http () ## Factory mode # class Factory: # def CreateA (self): # return BaseA () # def CreateB (self): # return BaseB () #### Singleton mode # class Logger (object): # log = None # @ staticmethod # def new (): ## import threading # thread security # mylock = threading. RLock () # mylock. acquire () # if not Logger. log: # Logger. log = Logger () # mylock. release () # return Logger. log # def write (self, v): # print 'logger ', v # if _ name _ = "_ main __": # a = Factory (). createA () # B = Factory (). createB () # objS = Observer () # objS. register (a) # objS. register (B) #. compute () # B. compute () # objS. Y () # b1 = B1 () # b1.http () # Logger. new (). log. write ('V ')