[Python design mode] 6th Chapter dress collocation System--decoration mode

Source: Internet
Author: User

Topic

Design a console program that can be paired with hip-hop style (T-shirts, baggy pants, sneakers) or white-collar style (suits, ties, shoes) and display, similar to the QQ show.

Base version
class Person():        def __init__(self, name):        self.name = name        def wear_T_shirts(self):        print("T恤")        def wear_big_trouser(self):        print("垮裤")            def wear_sneakers(self):        print("运动鞋")        def wear_suit(self):        print("西装")            def wear_tie(self):        print("领带")            def wear_leather_shoes(self):        print("皮鞋")        def show(self):        print("装扮的{}".format(self.name))

Client code

def main():    hezhang = Person("张贺")    print("第一种装扮")    hezhang.wear_T_shirts()    hezhang.wear_big_trouser()    hezhang.wear_sneakers()    hezhang.show()        print("第二种装扮")    hezhang.wear_suit()    hezhang.wear_tie()    hezhang.wear_leather_shoes()    hezhang.show()main()
第一种装扮T恤垮裤运动鞋装扮的张贺第二种装扮西装领带皮鞋装扮的张贺
Comments
    • Only basic functions are implemented
    • What do I need to do if I add a "Superman" outfit? You need to change the code in the Person class;
    • If the person class in addition to wearing clothes, but also support eating, sleeping and other functions, how to do? You need to change the code in the Person class;
    • In conclusion, it is necessary to separate the category of "dress" from "person".
Improved version 1.0--human clothing separation
class Person():        def __init__(self, name):        self.name = name        def show(self):        print("装扮的{}".format(self.name))from abc import ABCMeta, abstractmethodclass Finery(metaclass=ABCMeta):        @abstractmethod    def show(self):        pass    class TShirts(Finery):        def show(self):        print("T恤")class BigTrouser(Finery):        def show(self):        print("垮裤")        class Sneakers(Finery):        def show(self):        print("运动鞋")        class Suit(Finery):        def show(self):        print("西装")        class Tie(Finery):        def show(self):        print("领带")        class LeatherShoes(Finery):        def show(self):        print("皮鞋")

Client code

def main():    hezhang = Person("张贺")    print("第一种装扮")    t_shirts = TShirts()    big_trouser = BigTrouser()    sneakers = Sneakers()        t_shirts.show()    big_trouser.show()    sneakers.show()    hezhang.show()        print("第二种装扮")    suit = Suit()    tie = Tie()    leather_shoes = LeatherShoes()    suit.show()    tie.show()    leather_shoes.show()    hezhang.show()main()
第一种装扮T恤垮裤运动鞋装扮的张贺第二种装扮西装领带皮鞋装扮的张贺
Comments

Analyze the following code:

    hezhang = Person("张贺")    t_shirts = TShirts()    big_trouser = BigTrouser()    sneakers = Sneakers()        t_shirts.show()    big_trouser.show()    sneakers.show()    hezhang.show()

The description in natural language is:

    • The first instance of hezhang this human, accurately speaking, is not clothed human beings;
    • Re-instantiate and put on a variety of clothes, t-shirts, trousers, sports shoes, etc.
    • Show it again hezhang ;

But there seems to be no relationship between clothing and people, so how to express it in code:

    • Instantiation of naked human beings
    • Put a T-shirt on for naked humans
    • Wear pants for people wearing T-shirts
    • Put on sneakers for people wearing T-shirts and baggy pants.

This requires a decorative pattern.

Decoration mode

Decorative mode, in order to dynamically add some additional responsibilities to an object, the decorative mode is more flexible than the generation of subclasses in terms of the added functionality [DP].

There are several main components of the decorative pattern:

    • Component Class Component: Defines an object interface that can dynamically add responsibilities to these objects;
    • Specific Component Class Concretcomponent: Define a specific object, you can also add some responsibilities to the object;
    • Adornment class Decorator: Decorate abstract class, inherit component, extend the function of component class from outer class, for component, need not know the existence of decorator;
    • Concrete Decoration class Concretdecorator: Concrete decoration class, add duty for component

expressed in code:

From ABC import Abcmeta, Abstractmethodclass Component (Metaclass=abcmeta): "" "Component class Component: Defines an object interface that can dynamically add responsibilities to these objects "" "@abstractmethod def operation (self): Pass class Concretecomponent (Component):" "" Specific component Class C Oncretcomponent: Defines a specific object, or can add some responsibility to the object "" "Def Operation (self): print (" Operation of the specific component ") Class Decorator (C omponent): "" "Decoration class Decorator: Decorate abstract class, inherit component, extend the function of component class from outer class, for component, need not know the existence of decorator;" "Def __in        It__ (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 class Concretdecorator: Specific decoration class, add responsibility for Component" "" Def __init__ (self): Self.added_operation = "A: Specific decoration Class A exclusive operation" Def operation (self): super (). Operation () print (self.ad Ded_operation) PRInt ("A: the operation of the specific decorative object A") class Concretedecratorb (Decorator): "" "" "" "Decorative class Concretdecorator: Concrete decoration class, for component add job "" "Def __init__ (self): self.added_operation =" B: specific decoration class B exclusive Operation "Def operation (self): super ( ). Operation () print (self.added_operation) print ("B: operation of specific Decorative object B")
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()
具体组件的操作A:具体装饰类A独有操作A:具体装饰对象A的操作B:具体装饰类B独有操作B:具体装饰对象B的操作
Improved version 2.0--decoration mode
From ABC import abcmeta,abstractmethodclass person (): "" "Character class (Component Class)" "" Def __init__ (self, name): SELF.N    AME = Name def show (self): print ("Dress Up {}". Format (self.name)) class finery (person): "" "Costume Class (decoration Class) "" "Def __init__ (self): self.component = None def decorate (self, component): Self.component = C Omponent def Show (self): if self.component! = None:self.component.show () clas s Tshirts (finery): "" "" Concrete Decoration Class "" "Def Show (self): print (" T-shirt ") super (). Show () class Bigtrouser (Fine RY): "" "Concrete Decoration Class" "" Def Show (self): print ("Down Pants") super (). Show () class sneakers (Fine     RY): "" "" "", "" "" "Def Show (self): print (" Sneakers ") super (). Show () class Suit (finery):" "    Specific decoration Class "" "Def Show (self): print (" Suit ") super (). Show () class Tie (finery):" "" Concrete decoration class  "" "Def Show (self):      Print ("Tie") super (). Show () class Leathershoes (finery): "" "Concrete Decoration Class" "" Def Show (self): Print ("Leather Shoes") super (). Show ()

Client code

def main():    hezhang = Person("张贺")    t_shirts = TShirts()    big_trouser = BigTrouser()    sneakers = Sneakers()        t_shirts.decorate(hezhang)    big_trouser.decorate(t_shirts)    sneakers.decorate(big_trouser)    sneakers.show()    main()
运动鞋垮裤T恤装扮的张贺
Comments

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

    • Instantiation of naked human beings
    • Put a T-shirt on for naked humans
    • Wear pants for people wearing T-shirts
    • Put on sneakers for people wearing T-shirts and baggy pants.

So, a decorative model is a way to add more functionality to an already functional dynamic, placing each function to be decorated in a separate class, and having the class wrap the object it is decorating, so that when special behavior is required, the client code can wrap the object in order, using the adornment function, as needed, at run time.

The advantage of decorating mode is that the decoration function of the class is removed from the class, which simplifies the original class and effectively separates the class from the other 核心职责 装饰功能 . It can also remove repetitive decorative logic in related classes, where a decorative function can be used for several different classes.

[Python design mode] 6th Chapter dress collocation System--decoration mode

Related Article

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.