Decorate
一、定义:
Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality.
将额外的功能以动态的方式附于某物件身上,使不必进行subclassing就能扩展功能。
二、使用
Decorate的实质是将某一对象拿出来,在别的类中扩展,添加附加功能,再在调用类中调用,相当于拿来一个装饰过的object(该object已经相对于原object扩展了功能)。
使用情形一:A类中有方法func1,调用类C需要func1,但又需要更多功能;于是,定义类B,在B中引用A对象,并再写一个func1方法,添加需要扩展的功能。(当然,也可以通过继承来实现)。
实例代码如下:
public class Decorate
{
public static void main(String[] args)
{
Person p = new Person();
//p.eat();
NewPerson p1 = new NewPerson(p);
p1.eat();
}
}
class Person
{
public void eat()
{
System.out.println("吃白饭");
}
}
//这个类的出现是为了增强Person而出现的
class NewPerson
{
private Person p;
NewPerson(Person p)
{
this.p = p;
}
public void eat()
{
System.out.println("开胃酒");
p.eat();
System.out.println("甜点");
}
}
/*
* //继承也可以解决这个问题
* class NewPerson2 extends Person
* {
* public void eat()
* {
* System.out.println("开胃酒");
* super.eat(); System.out.println("甜点");
* }
* }
*/
使用情形二:
解说:BufferReader中的参数Reader对象在FileReader中经过装饰传进来。