您的位置:首页 > 编程语言 > Java开发

Java设计模式----------装饰模式(Decorator)

2014-01-22 11:07 651 查看

一:介绍

        (1)装饰 模式又叫做包装模式,是继承的一种替代模式。

        (2)一般在一些的集中条件下,使用装饰模式:

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

1.在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责。

2.处理那些可以撤销的职责。

3.当不能采用生成子类的方法进行扩充时。

二:角色设置

在装饰模式下,每一个类扮演者自己的特殊角色:
(1)抽象构建角色:(一个接口类--interface),用于规范接收附加责任的对象。
(2)具体的构建角色:(就是你要包装的类)。实现interface接口。
(3)装饰角色:(一个实现interface的抽象类)。
(4)具体的装饰者:负责给具体的构建角色(2)包装。

三:代码片分析

(1)抽象构建者:

public interface Person {

public void eat();
}

(2)具体的构建角色:
public class Man implements Person {

@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("man 要吃牛肉");

}

}


(3)装饰角色:
public abstract class Decorator implements Person {

protected Person person;

public void setPerson(Person person){
this.person = person;
}
public void eat(){
person.eat();
}

}


(4)具体的装饰者:

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();

}

}

四:运行结果:



扫一扫下面的二维码,关注我们,每天分享专业的技术文章,让您利用碎片时间,分分钟提升自己的bigger。



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: