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: