JAVA 装饰模式-2016软件设计师下半年考试真题

题目要求:打印发票头、内容、底部的要求

BTW,八成这次软考又挂了…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Invoice{
public void printInvoice(){
System.out.println("this is content");
}
}
class Decorator extends Invoice{
protected Invoice ticket;
public Decorator (Invoice t){
ticket=t;
}
public void printInvoice(){
if(ticket!=null){
ticket.printInvoice();
}
}
}
class HeaderDecorator extends Decorator{
public HeaderDecorator(Invoice t){
super(t);
}
public void printInvoice(){
System.out.println("this is the header");
super.printInvoice();
}
}
class FooterDecorator extends Decorator{
public FooterDecorator(Invoice t){
super(t);
}
public void printInvoice(){
super.printInvoice();
System.out.println("this is the footer");
}
}
public class zhuangshi {
public static void main(String[] args){
Invoice t =new Invoice();
Invoice ticket;
ticket=new FooterDecorator(new HeaderDecorator(t));
ticket.printInvoice();
System.out.println("=====================");
ticket=new FooterDecorator(new HeaderDecorator(new Decorator(null)));
ticket.printInvoice();
}
}

这么写也行 ,不知道哪个算标准答案

1
2
3
4
5
6
7
Invoice t =new Invoice();
Invoice ticket;
ticket=new HeaderDecorator(new FooterDecorator(t));
ticket.printInvoice();
System.out.println("=====================");
ticket=new HeaderDecorator(new FooterDecorator(null));
ticket.printInvoice();

结果

图片描述