23 Design Modes (20): Decorative mode

Source: Internet
Author: User

Overview:

Add some extra responsibilities to an object dynamically. For added functionality, the decorator mode is more flexible than generating subclasses.

Type: Structural mode.

Class Diagram:

Applicability:

1. Add responsibilities to a single object in a dynamic, transparent manner without affecting other objects.

2. Handle the duties that can be undone.

3. When a method of generating subclasses cannot be used for expansion.

Participants:

1.Component

Defines an object interface that can dynamically add responsibilities to these objects.

2.ConcreteComponent

Defines an object that can add some responsibility to the object.

3.Decorator

Maintains a pointer to the component object and defines an interface that is consistent with the component interface.

4.ConcreteDecorator

Add responsibilities to the component.

Example:

ComponentPublicInterfaceperson {void eat ();} ConcretecomponentPublicClassMansImplementsperson {PublicvoidEat () {System.out.println ("The man is Eating"); }}decoratorPublicAbstractClassDecoratorImplementsperson {protected person person;PublicvoidSetperson (person person) {This.person = person; }PublicvoidEat () {person.eat ();}} ConcretedecoratorPublicClassMandecoratoraExtendsDecorator {PublicvoidEat () {Super.eat (); Reeat (); System.out.println ("Mandecoratora class"); }PublicvoidReeat () {System.out.println ("Eat another Meal"); }}PublicClassMandecoratorbextends decorator {public void eat () {super.eat (); System.out.println ( "==============="); System.out.println ( "Mandecoratorb class");}} Test public class test {public static  void main (string[] args) {man mans = new Man (); Mandecoratora md1 = new Mandecoratora (); Mandecoratorb MD2 = new Mandecoratorb (); Md1.setperson (man); Md2.setperson (MD1); Md2.eat () ; }} 

Result

男人在吃再吃一顿饭ManDecoratorA类===============ManDecoratorB类

23 Design Modes (20): Decorative mode

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.