------- android培训、java培训、期待与您交流! ----------
装饰类的特点:
1,它必须具有一个装饰的对象。
2,它必须拥有与被装饰对象相同体系(接口)。
3,它可以给被装饰对象添加额外的功能。
4,用一句话总结就是:保持体系一致,增强性能。
装饰模式和继承的比较:
装饰模式 | 继承 |
用来扩展特定对象的功能 | 用来扩展一类对象的功能 |
不需要子类 | 需要子类 |
动态地 | 静态地 |
运行时分配职责 | 编译时分派职责 |
防止由于子类而导致的复杂和混乱 | 导致很多子类产生,在一些场合,报漏类的层次 |
更多的灵活性 | 缺乏灵活性 |
MyReader//专门用于读取数据的类。
|--MyTextReader
|--MyBufferTextReader
|--MyMediaReader
|--MyBufferMediaReader
|--MyDataReader
|--MyBufferDataReader
class MyBufferReader
{
MyBufferReader(MyTextReader text)
{}
MyBufferReader(MyMediaReader media)
{}
}
上面这个类扩展性很差。
找到其参数的共同类型。通过多态的形式。可以提高扩展性。
class MyBufferReader extends MyReader
{
private MyReader r;
MyBufferReader(MyReader r)
{}
}
MyReader//专门用于读取数据的类。
|--MyTextReader
|--MyMediaReader
|--MyDataReader
|--MyBufferReader
以前是通过继承将每一个子类都具备缓冲功能。
那么继承体系会复杂,并不利于扩展。
现在优化思想。单独描述一下缓冲内容。
将需要被缓冲的对象。传递进来。也就是,谁需要被缓冲,谁就作为参数传递给缓冲区。
这样继承体系就变得很简单。优化了体系结构。
装饰模式比继承要灵活。避免了继承体系臃肿。
而且降低了类于类之间的关系。
装饰类因为增强已有对象,具备的功能和已有的是相同的,只不过提供了更强功能。
所以装饰类和被装饰类通常是都属于一个体系中的。
装饰类例子:
public class Test{
public static void main(String args[]){
Animal animal=new Dog("dog",3);
TestDecorator decorator=new TestDecorator(animal);
decorator.voicePrint();
animal=new Cat("cat",2);
decorator=new TestDecorator(animal);
decorator.voicePrint();
animal=new Monkey("monkey",1);
decorator=new TestDecorator(animal);
decorator.voicePrint();
}
}
abstract class Animal{
String name;
int age;
public void voicePrint(){};
}
class TestDecorator extends Animal{
Animal animal;
TestDecorator(Animal animal){
this.animal=animal;
}
public void voicePrint(){
System.out.print("i`m "+animal.name + " ,this year is "+animal.age+", and my voice is:");
animal.voicePrint();
}
public String getName(){
return animal.name;
}
/*
* other methods...
*/
}
class Monkey extends Animal{
Monkey(String name,int age){
this.name=name;
this.age=age;
}
public void voicePrint(){
System.out.println("zhizhi...");
}
}
class Dog extends Animal{
Dog(String name,int age){
this.name=name;
this.age=age;
}
public void voicePrint(){
System.out.println("wangwang...");
}
}
class Cat extends Animal{
Cat(String name,int age){
this.name=name;
this.age=age;
}
public void voicePrint(){
System.out.println("miaomiao...");
}
}
输出结果:
i`m dog ,this year is 3, and my voice is:wangwang...
i`m cat ,this year is 2, and my voice is:miaomiao...
i`m monkey ,this year is 1, and my voice is:zhizhi...