github Address :https://github.com/cheesezh/python_design_patterns

subject

Design a console program , It can be paired with hip-hop style (T T-shirt , loose , Sports shoes ) Or white collar style ( Suit , necktie , leather shoes ) And show , similar QQ Show like that .

Basic version

class Person():

    def __init__(self, name):
self.name = name def wear_T_shirts(self):
print("T T-shirt ") def wear_big_trouser(self):
print(" loose ") def wear_sneakers(self):
print(" Sports shoes ") def wear_suit(self):
print(" Suit ") def wear_tie(self):
print(" necktie ") def wear_leather_shoes(self):
print(" leather shoes ") def show(self):
print(" Dressed up {}".format(self.name))

Client code

def main():
hezhang = Person(" Zhang He ")
print(" First look ")
hezhang.wear_T_shirts()
hezhang.wear_big_trouser()
hezhang.wear_sneakers()
hezhang.show() print(" Second look ")
hezhang.wear_suit()
hezhang.wear_tie()
hezhang.wear_leather_shoes()
hezhang.show() main()
 First look 
T T-shirt
loose
Sports shoes
Dressed up Zhang he
Second look
Suit
necktie
leather shoes
Dressed up Zhang he

comment

  • Only the basic functions are realized
  • If you add “ superman ” Dress up , What needs to be done ? Need to be in Person Class ;
  • If Person Except for clothes , And support eating , Sleep and other functions , What needs to be done ? Need to be in Person Class ;
  • Sum up , Need to put “ dress ” Classes and “ people ” Class separation .

Improved version 1.0—— Separation of human and clothing

class Person():

    def __init__(self, name):
self.name = name def show(self):
print(" Dressed up {}".format(self.name)) from abc import ABCMeta, abstractmethod class Finery(metaclass=ABCMeta): @abstractmethod
def show(self):
pass class TShirts(Finery): def show(self):
print("T T-shirt ") class BigTrouser(Finery): def show(self):
print(" loose ") class Sneakers(Finery): def show(self):
print(" Sports shoes ") class Suit(Finery): def show(self):
print(" Suit ") class Tie(Finery): def show(self):
print(" necktie ") class LeatherShoes(Finery): def show(self):
print(" leather shoes ")

Client code

def main():
hezhang = Person(" Zhang He ")
print(" First look ")
t_shirts = TShirts()
big_trouser = BigTrouser()
sneakers = Sneakers() t_shirts.show()
big_trouser.show()
sneakers.show()
hezhang.show() print(" Second look ")
suit = Suit()
tie = Tie()
leather_shoes = LeatherShoes()
suit.show()
tie.show()
leather_shoes.show()
hezhang.show() main()
 First look 
T T-shirt
loose
Sports shoes
Dressed up Zhang he
Second look
Suit
necktie
leather shoes
Dressed up Zhang he

comment

Analyze the following code :

    hezhang = Person(" Zhang He ")
t_shirts = TShirts()
big_trouser = BigTrouser()
sneakers = Sneakers() t_shirts.show()
big_trouser.show()
sneakers.show()
hezhang.show()

To describe it in natural language is :

  • First instantiate hezhang This human being , Accurately speaking , It's human beings without clothes ;
  • Then instantiate and put on all kinds of clothes ,T T-shirt , loose , Sneakers, etc ;
  • Show it again hezhang;

But there doesn't seem to be any relationship between clothing and people , So how to code :

  • We're naked humans
  • For naked humans T T-shirt
  • For wearing T People in T-shirt wear baggy pants
  • For wearing T T-shirt , People with baggy pants put on sports shoes

This requires decorative patterns .

Decoration mode

Decoration mode , In order to dynamically add some additional responsibilities to an object , In terms of adding features , Decoration patterns are more flexible than subclasses [DP].

The decoration pattern has the following main components :

  • Component class Component: Define an object interface , You can add responsibilities to these objects dynamically ;
  • Specific component classes ConcretComponent: Defines a concrete object , You can also add some responsibilities to this object ;
  • Decoration Decorator: Decoration abstract class , Inherit Component, Extend... From an outer class Component Class , about Component for , There is no need to know Decorator The existence of ;
  • Concrete decoration ConcretDecorator: Concrete decoration , by Component Add responsibilities

In code :

from abc import ABCMeta, abstractmethod

class Component(metaclass=ABCMeta):
"""
Component class Component: Define an object interface , You can add responsibilities to these objects dynamically
"""
@abstractmethod
def operation(self):
pass class ConcreteComponent(Component):
"""
Specific component classes ConcretComponent: Defines a concrete object , You can also add some responsibilities to this object
"""
def operation(self):
print(" Operation of specific components ") class Decorator(Component):
"""
Decoration Decorator: Decoration abstract class , Inherit Component, Extend... From an outer class Component Class , about Component for , There is no need to know Decorator The existence of ;
"""
def __init__(self):
self.component = None def set_component(self, component):
self.component = component def operation(self):
if self.component != None:
self.component.operation() class ConcreteDecratorA(Decorator):
"""
Concrete decoration ConcretDecorator: Concrete decoration , by Component Add responsibilities
"""
def __init__(self):
self.added_operation = "A: Concrete decoration A Unique operation " def operation(self):
super().operation()
print(self.added_operation)
print("A: Specific decoration object A The operation of ") class ConcreteDecratorB(Decorator):
"""
Concrete decoration ConcretDecorator: Concrete decoration , by Component Add responsibilities
"""
def __init__(self):
self.added_operation = "B: Concrete decoration B Unique operation " def operation(self):
super().operation()
print(self.added_operation)
print("B: Specific decoration object B The operation of ")
def main():
component = ConcreteComponent()
decorator_a = ConcreteDecratorA()
decorator_b = ConcreteDecratorB() decorator_a.set_component(component)
decorator_b.set_component(decorator_a)
decorator_b.operation() main()
 Operation of specific components 
A: Concrete decoration A Unique operation
A: Specific decoration object A The operation of
B: Concrete decoration B Unique operation
B: Specific decoration object B The operation of

Improved version 2.0—— Decoration mode

from abc import ABCMeta,abstractmethod

class Person():
"""
The character class ( Component class )
"""
def __init__(self, name):
self.name = name def show(self):
print(" Dressed up {}".format(self.name)) class Finery(Person):
"""
Clothing ( Decoration )
"""
def __init__(self):
self.component = None def decorate(self, component):
self.component = component def show(self):
if self.component != None:
self.component.show() class TShirts(Finery):
"""
Concrete decoration
"""
def show(self):
print("T T-shirt ")
super().show() class BigTrouser(Finery):
"""
Concrete decoration
"""
def show(self):
print(" loose ")
super().show() class Sneakers(Finery):
"""
Concrete decoration
"""
def show(self):
print(" Sports shoes ")
super().show() class Suit(Finery):
"""
Concrete decoration
"""
def show(self):
print(" Suit ")
super().show() class Tie(Finery):
"""
Concrete decoration
"""
def show(self):
print(" necktie ")
super().show() class LeatherShoes(Finery):
"""
Concrete decoration
"""
def show(self):
print(" leather shoes ")
super().show()

Client code

def main():
hezhang = Person(" Zhang He ")
t_shirts = TShirts()
big_trouser = BigTrouser()
sneakers = Sneakers() t_shirts.decorate(hezhang)
big_trouser.decorate(t_shirts)
sneakers.decorate(big_trouser)
sneakers.show() main()
 Sports shoes 
loose
T T-shirt
Dressed up Zhang he

comment

The above client code can be described in natural language as :

  • We're naked humans
  • For naked humans T T-shirt
  • For wearing T People in T-shirt wear baggy pants
  • For wearing T T-shirt , People with baggy pants put on sports shoes

therefore , Decoration model is a way to dynamically add more functions to existing functions , It puts each function to be decorated in a separate class , And let this class wrap the object it's going to decorate , therefore , When special actions need to be performed , Client code can be selected according to the needs at runtime , Use decoration function to package objects in order .

The advantage of the decorative pattern is , Move the decoration function of a class out of the class , This simplifies the original class , Effectively put the class into Core responsibilities and Decorative function It's different . And it can remove the repetitive decoration logic in related classes , That is, a decoration function can be used by many different classes .

[Python Design patterns ] The first 6 Chapter Clothing matching system —— More articles on decoration patterns

  1. [Python Design patterns ] The first 21 Chapter Family planning —— The singleton pattern

    github Address :https://github.com/cheesezh/python_design_patterns The singleton pattern The singleton pattern (Singleton Pattern) Is a common software design pattern ...

  2. [Python Design patterns ] The first 22 Chapter Mobile phone model & Software version —— Bridging mode

    github Address :https://github.com/cheesezh/python_design_patterns Tightly coupled program evolution subject 1 Programming simulates the following scenarios , There is one N Brand mobile phone , Play a little game on it . ...

  3. [Python Design patterns ] The first 1 Chapter Calculator —— Simple factory model

    github Address :https://github.com/cheesezh/python_design_patterns Let me write it out front """ When I was reading < Design die ...

  4. [Python Design patterns ] The first 28 Chapter Men and women —— Visitor mode

    github Address :https://github.com/cheesezh/python_design_patterns subject Use the program to simulate the following different situations : When men succeed , There's probably a great woman behind her : Women succeed ...

  5. [Python Design patterns ] The first 26 Chapter One thousand thousand , Inner sharing —— The flyweight pattern

    github Address :https://github.com/cheesezh/python_design_patterns background Yes 6 A customer wants to be a product display website , among 3 I want to be like tmall mall " E-commerce wind ...

  6. [Python Design patterns ] The first 25 Chapter The United Nations maintains world peace —— Intermediary model

    github Address :https://github.com/cheesezh/python_design_patterns Background The United Nations is the intermediary in the world , The relationship between countries is complex , Similar to different objects and to ...

  7. [Python Design patterns ] The first 18 Chapter Game character backup —— Memo mode

    github Address :https://github.com/cheesezh/python_design_patterns subject Use the code to simulate the following scenario , A character has life force , aggressivity , Defense and other data , Fight Bos ...

  8. [Python Design patterns ] The first 17 Chapter The translator in the program —— Adapter pattern

    github Address :https://github.com/cheesezh/python_design_patterns Adapter pattern Adapter pattern , Convert the interface of one class to another that the customer wants .Adapte ...

  9. [Python Design patterns ] The first 14 Chapter Here comes the boss —— Observer mode

    github Address :https://github.com/cheesezh/python_design_patterns subject Use the program to simulate the following scenario , In an office , When the boss comes in , The front desk Secretary secretly informed the office ...

Random recommendation

  1. 【Java A daily topic 】20170105

    20170104 For problem analysis, please click below today's questions "[Java A daily topic ]20170105" see ( The problem is solved in the official account , official account ID:weknow619) package Jan2017; ...

  2. erlang Access to remote shell

    Two ways erl -name aaa@127.0.0.1 -setcookie erl -name bbb@127.0.0.1 -setcookie ctrl + g Get into jcl Pattern h view help r ' ...

  3. Flash AIR14 export ipa To Mac Upper iOS Simulator test

    you 're right ! You read that right ! My blog is about Flash AIR Of ! ---------------- Boring dividing line ------------------ My friend has been studying recently Flash AIR for iOS Development , You want me to help you ...

  4. cf- Formula show

    A. Again Twenty Five! time limit per test 0.5 seconds memory limit per test 64 megabytes input stand ...

  5. Java Grammatical details - Memory and enumeration

    Catalog Java apply DirectBuffer ByteBuffer Of position,limit,capacity,flip The relationship between operations Enumerations implement singleton patterns Java apply DirectBuffer /*- ...

  6. MXNET: Convolutional neural networks

    Introduce several in the past few years ImageNet competition ( A famous computer vision competition ) Deep convolution neural network with excellent results . LeNet LeNet It is proved that the gradient descent training convolutional neural network can achieve the most advanced results of handwritten digit recognition . ...

  7. 【 Code audit 】XIAOCMS_ backstage database.php Page exists SQL Inject holes

      0x00 Environmental preparation XIAOCMS Official website : http://www.xiaocms.com/ Website source version :XiaoCms ( Release time :2014-12-29) Program source download :http://www.xi ...

  8. DELPHI Sending and receiving of custom messages in

    DELPHI Message handling mechanism in Delphi yes Borland The company offers a brand new WINDOWS Programming development tools . Because of its flexible and reusable object orientation Pascal(object-orientedpasca ...

  9. Cookie Do session management

    One . The concept of conversation Conversation can be simply understood as : Users open a browser , Click on multiple hyperlinks , Access multiple servers web resources , Then close the browser , The whole process is called a conversation . Stateful conversation : A classmate came to the classroom , Come back to the classroom next time , We will know that this classmate once ...

  10. Explain in detail Android Network communication (HttpUrlConnection and HttpClient)

    Preface ,Android There are two ways of network communication : Use Socket perhaps HTTP, In today's article, we will explain in detail how to use HTTP Network communication realized ,HTTP There are two programming methods : (1)HttpUrlConnection: ...