一直知道java io里面用到得到装饰器模式但是一直很模糊,最近看了《设计模式之禅》才明白其中道理。。。自己太笨没办法,无奈记忆力又不好所以记下来。
以下是类图:
下面对照我们来具体仿照下设计模式之禅的例子(像老爸汇报期末考试成绩让老爸签字,如果让老爸签字必须对成绩添加下装饰)对照下类图:
首先是Component类对应的是SchoolReport (汇报成绩)
package com.xin.parttern.decorator; public abstract class SchoolReport { public abstract void report(); public abstract void sign(String name); }
ConcreateComponent对应的是FouthSchoolGradeReport(具体汇报成绩)
package com.xin.parttern.decorator; public class FouthSchoolGradeReport extends SchoolReport { @Override public void report() { System.out.println("成绩是 60分,排名38"); } @Override public void sign(String name) { System.out.println("家长签字:"+name); } }
Decorator对应的是Decorator(成绩装饰类)
package com.xin.parttern.decorator; public abstract class Decorator extends SchoolReport { private SchoolReport schoolReport; public Decorator(SchoolReport schoolReport) { this.schoolReport = schoolReport; } @Override public void report() { schoolReport.report(); } @Override public void sign(String name) { schoolReport.sign(name); } }
ConcreateDecorator类对应两个具体装饰类 :
package com.xin.parttern.decorator; public class HighScoreDecorator extends Decorator { public HighScoreDecorator(SchoolReport schoolReport) { super(schoolReport); } @Override public void report() { this.reportHighScore(); super.report(); } private void reportHighScore(){ System.out.println("最高成绩才70分。"); } }
package com.xin.parttern.decorator; public class SortDecortor extends Decorator{ public SortDecortor(SchoolReport schoolReport) { super(schoolReport); // TODO Auto-generated constructor stub } @Override public void report() { reportSort(); super.report(); } private void reportSort(){ System.out.println("班里面45人排名37。"); } }
最后是父亲(Main)使用者:
package com.xin.parttern.decorator; public class Father { public static void main(String[] args) { SchoolReport schoolReport; schoolReport = new FouthSchoolGradeReport(); schoolReport = new HighScoreDecorator(schoolReport); schoolReport = new SortDecortor(schoolReport); schoolReport.report(); schoolReport.sign("老X"); } }
看上面标红色字体的是在汇报成绩之前的装饰。具体看下两个具体装饰器的report方法,先去调用自己的report在调用父类的report。在Father类中SortDecortor父类是HighScoreDecorator,而HighScoreDecorator父类是FouthSchoolGradeReport,所以输入的运行结果是:
班里面45人排名37。 (装饰)
最高成绩才70分。 (装饰)
成绩是 60分,排名38
家长签字:老X
在对照下java io的
InputStream
FilterInputStream
以上这几个类。
inputStream显示是Component ,FIlterInputStream 为文例子中的Decorator ,剩下的bufferedInputStream等为ConcreateComponent。
具体看下IO具体装饰器的代码是否和上面的例子对照。相信很快就能明白装饰器模式。