(1)装饰 模式又叫做包装模式,是继承的一种替代模式。
(2)一般在一些的集中条件下,使用装饰模式:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
1.在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责。
2.处理那些可以撤销的职责。
3.当不能采用生成子类的方法进行扩充时。
public interface Person {
public void eat();
}
public class Man implements Person {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("man 要吃牛肉");
}
}public abstract class Decorator implements Person {
protected Person person;
public void setPerson(Person person){
this.person = person;
}
public void eat(){
person.eat();
}
}
public class ManDecoratorA extends Decorator{
public void eat(){
super.eat();
reEat();
System.out.println("ManDecoratorA");
}
private void reEat() {
System.out.println("再吃一顿");
}
}(5)主类: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();
}
}
Java设计模式----------装饰模式(Decorator)
原文:http://blog.csdn.net/nefuyang/article/details/9793509