Java design patterns ---------- Decorator)

Source: Internet
Author: User

I. Introduction

(1) The decoration mode, also called the packaging mode, is an alternative mode of inheritance.

(2) The decoration mode is generally used in some concentrated conditions:

Dynamically add some additional responsibilities to an object. The Decorator mode is more flexible than the subclass generation function.

1. Add roles to a single object dynamically and transparently without affecting other objects.

2. Handle the revoking responsibilities.

3. When the subclass generation method cannot be used for expansion.

2: In the decoration mode, each class plays its own special role: (1) Abstract build role: (an interface class -- interface), used to standardize the objects receiving additional responsibilities. (2) The specific build role: (is the class you want to wrap ). Implement the interface. (3) Decoration role: (an abstract class implementing the interface ). (4) Specific decorators: Responsible for packaging specific building roles (2. Iii. Code slice analysis (1) Abstraction builder:
public interface Person {        public void eat();}

(2) specific build roles:
Public class Man implements Person {@ Overridepublic void eat () {// TODO Auto-generated method stubSystem. out. println ("man wants beef ");}}

(3) Decoration role:
public abstract class Decorator implements Person {    protected Person person;        public void setPerson(Person person){    this.person = person;    }    public void eat(){    person.eat();    }}

(4) Specific decorators:
Public class ManDecoratorA extends Decorator {public void eat () {super. eat (); reEat (); System. out. println ("ManDecoratorA");} private void reEat () {System. out. println ("another meal ");}}
(5) Main class:
public class Text {public static void main(String[] args) {Man man = new Man();ManDecoratorA ma = new ManDecoratorA();//ManDecoratorB mb = new ManDecoratorB();ma.setPerson(man);ma.eat();}}

Iv. Running result:



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.