1. 程式人生 > >設計模式----裝飾者模式(decorator pattern)

設計模式----裝飾者模式(decorator pattern)

SchoolReport.java程式碼如下:

package com.designPattern.decorator;

public abstract class SchoolReport {

public abstract void report();

public abstract void sign(String name);
}



FouthGradeSchoolReport.java程式碼如下:

package com.designPattern.decorator;

public class FouthGradeSchoolReport extends SchoolReport{

@Override
public void report() {
System.out.println("========以下是成績單原裝內容!============");
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println("+++++++++++++++++++++++++++++++++++");
System.out.println("========以上是成績單原裝內容!============");
}

@Override
public void sign(String name) {
System.out.println("家長簽名為:" +name);

}

}



Decorator.java程式碼如下:

package com.designPattern.decorator;

public abstract class Decorator extends SchoolReport{

private SchoolReport schoolReport;

public Decorator(SchoolReport schoolReport){
this.schoolReport =schoolReport;
}

public void report(){
this.schoolReport.report();
}

public void sign(String name){
this.schoolReport.sign(name);
}
}



HighScoreDecorator.java程式碼如下:

package com.designPattern.decorator;

public class HighScoreDecorator extends Decorator{

public HighScoreDecorator(SchoolReport schoolReport) {

super(schoolReport);
}

public void reportHighScore(){
System.out.println("這次語文成績最高是75,數學是78,自然是80");
}

public void report(){
this.reportHighScore();
super.report();
}
}



SortDecorator.java程式碼如下:

package com.designPattern.decorator;

public class SortDecorator extends Decorator{

public SortDecorator(SchoolReport schoolReport) {

super(schoolReport);
}

private void reportSort(){
System.out.println("我排名第38名");
}

@Override
public void report() {
super.report();
this.reportSort();
}

}



Father.java程式碼如下:

package com.designPattern.decorator;

public class Father {

public static void main(String[] args) {

SchoolReport schoolReport;

schoolReport = new FouthGradeSchoolReport();

schoolReport = new HighScoreDecorator(schoolReport);

schoolReport = new SortDecorator(schoolReport);

schoolReport.report();

schoolReport.sign("one'father");
}

}



執行結果如下:

這次語文成績最高是75,數學是78,自然是80
========以下是成績單原裝內容!============
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
========以上是成績單原裝內容!============
我排名第38名
家長簽名為:one'father