The decorator pattern
When we inherit a class we can get the part of its methods and properties, the decorator pattern to a certain extent as a solution alternative succession. It can extend the dynamic object and function transparency.
specification
Decorator mode requires the following three requirements.
1. decorator to be associated with a decorator.
2. decorator decorators to achieve the same interface.
3. For not require an enhanced method, the method can be invoked directly decorator.
for example
Definition of standardized interfaces
public interface animal {
public abstract void eat();
public abstract void exercise();
}
Implement the decorator interface
public class dog implements animal {
@Override
public void eat() {
System.out.println("啃骨头");
}
@Override
public void exercise() {
System.out.println("跑");
}
}
Association is to implement the interface and decorators decorators
the implements to Huskie class public Animal {
// Get the object is a decorator's
Private Dog D;
@Override
public void EAT () {
d.eat ();
}
@Override
public void Exercise () { d.exercise (); the System. Out.println ( "pushers" ); }
}
Feature
The decorator pattern relative to inherit in terms of more flexibility while achieving a variety of combinations.