Java Decorative design pattern

Source: Internet
Author: User

pass an object as a parameter and then wrap the object --- change the method or add some new behavior --- the decorative design pattern --- Decorator mode ---decorate model

Change a method:

1. by inheriting this class, and then overriding the method

2. create decorative objects by passing objects, and re-provide the corresponding methods in the decoration class
Disadvantages of Inheritance:

1. Single Inheritance

2. create a parent class object using the up shape, you can call the overridden method in the subclass, cannot use the original method in the parent class

3. if the parent object already exists, you cannot use the overridden method in the subclass

Disadvantages of decorative Design patterns:

may increase the redundancy of the code --- proxy mode

1 //Man's interface2  Public InterfacePerson {3 4     voideat ();5 6     voidsleep ();7 8 }9 Ten  One //Star of the realization class A  Public classStarImplementsPerson { -  -@SuppressWarnings ("Unused") the     PrivatePerson p; -  -      PublicStar (person p) { -          This. P =p; +     } -  + @Override A      Public voideat () { atSystem.out.println ("The Star eats the wild vegetables ~ ~ ~"); -     } -  - @Override -      Public voidsleep () { -System.out.println ("Bed count stars ~ ~ ~"); in     } -  to } +  - //Worker Realization Class the  Public classWorkerImplementsPerson { *  $ @OverridePanax Notoginseng      Public voideat () { -SYSTEM.OUT.PRINTLN ("The workers eat a good meal ~ ~ ~ and then eat one months of soil ~ ~ ~"); the     } +  A @Override the      Public voidsleep () { +System.out.println ("Bed count stars ~ ~ ~"); -     } $  $ } -  - //packaging workers into stars, but essentially workers or workers the  Public classPersondemo { - Wuyi      Public Static voidMain (string[] args) { the  -Worker p =NewWorker (); Wu  - p.eat (); About  $Star s =NewStar (p); -  - s.eat (); -  A p.eat (); +  the     } -  $}

Java Decorative design pattern

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.