理解聚集关系在代码中的体现。
package decorator_media;
public interface IMedia {
public void Play();
}
package decorator_media;
public abstract class VideoMedia implements IMedia {
public abstract void Play();
}
package decorator_media;
public class RM extends VideoMedia {
@Override
public void Play() {
System.out.println("Play VideoMedia with the type of RM");
}
}
package decorator_media;
public class MPEG extends VideoMedia {
@Override
public void Play() {
System.out.println("Play VideoMedia with the type of MPEG");
}
}
package decorator_media;
public abstract class VideoDecorator extends VideoMedia{
private VideoMedia videoMedia;
public VideoDecorator(VideoMedia _videoMedia) {
this.videoMedia = _videoMedia;
}
public void Play(){
this.videoMedia.Play();
}
}
package decorator_media;
public class CopyRightVideoDecorator extends VideoDecorator {
private CopyRight copyRight;
public CopyRightVideoDecorator(VideoMedia _videoMedia) {
super(_videoMedia);
}
public CopyRight getCopyRight() {
return copyRight;
}
public void setCopyRight(CopyRight copyRight) {
this.copyRight = copyRight;
}
public void Play(){
super.Play();
System.out.println(this.copyRight.getInfomation());
}
}
package decorator_media;
public class CopyRight {
private String infomation = "Copyright © 2010 Eric. All rights reserved.";
public String getInfomation() {
return infomation;
}
public void setInfomation(String infomation) {
this.infomation = infomation;
}
}
通过本例,我们可以看到Decorator模式与对象的Adapter模式的区别。
实现的区别:
1、 Decorator抽象类应继承要装饰的类,同时又聚合该类的实例对象;而对象的Adapter模式则只聚合,不继承;
2、 Decor模式并没有引入新的接口,除非要装饰的行为需要使用该接口;而对象的Adapter模式则引入了新的接口,以此来装配原有的对象,使其具有了新接口的方法;
因此,适用的场景也就有所不同:
1、 Decorator模式如其名,一般并不提供新的行为,而是在原有的行为上进行补充,即装饰的含义。
2、 Adapter模式则是为对象引入新的行为,使其匹配新的接口,即为适配的意义所在。