装饰者模式定义:动态地给对象添加一些额外的职责。
项目中需要扩展类而又不希望增加过多子类的情况下,可以考虑使用装饰者模式。
以下代码演示装饰者模式简单的实际运用:
定义一个抽象的Stationery类:
package com.ldl.cn.DecoratorModel;
public abstract class Stationery {
String description = "Unknown stationery";
public String getDescription(){
return description;
}
public abstract double cost();
}
定义一个StationeryBox继承Stationery:
package com.ldl.cn.DecoratorModel;
public class StationeryBox extends Stationery{
public StationeryBox() {
super();
description = "一个文具盒";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 20.00;
}
}
分别定义StationeryBox的子类Pen、Pencil:
package com.ldl.cn.DecoratorModel;
public class Pen extends StationeryBox{
Stationery stationery;
public Pen(Stationery stationery) {
super();
this.stationery = stationery;
}
public String getDescription(){
return stationery.getDescription()+",加钢笔";
}
public double cost(){
return stationery.cost()+30.00;
}
}
package com.ldl.cn.DecoratorModel;
public class Pencil extends StationeryBox{
Stationery stationery;
public Pencil(Stationery stationery) {
super();
this.stationery = stationery;
}
public String getDescription(){
return stationery.getDescription() + ",加铅笔";
}
public double cost(){
return stationery.cost() + 5.00;
}
}
编写测试类:
package com.ldl.cn.DecoratorModel;
public class TestDecoratorPattern {
public static void main(String[] args) {
Stationery stationery = new StationeryBox();
System.out.println(stationery.getDescription()+"共需花费:"+stationery.cost());
Stationery stationery2 = new StationeryBox();
stationery2 = new Pen(stationery2);
System.out.println(stationery2.getDescription()+"共需花费:"+stationery2.cost());
Stationery stationery3 = new StationeryBox();
stationery3 = new Pencil(stationery3);
System.out.println(stationery3.getDescription()+"共需花费:"+stationery3.cost());
Stationery stationery4 = new StationeryBox();
stationery4 = new Pen(stationery4);
stationery4 = new Pencil(stationery4);
System.out.println(stationery4.getDescription()+"共需花费:"+stationery4.cost());
}
}
运行结果:
一个文具盒共需花费:20.0
一个文具盒,加钢笔共需花费:50.0
一个文具盒,加铅笔共需花费:25.0
一个文具盒,加钢笔,加铅笔共需花费:55.0