模式介绍
装饰模式是使用一种对客户端透明的方式来动态地扩展对象的功能,同时它也是继承关系的一种替代方案之一。装饰模式相比生成子类更为灵活。
应用场景
需要透明且动态地扩展类的功能时。生活中也能看到很多装饰模式的例子,例如衣服上的装饰物,各种搭配等等。
代码例子
下面用一个房子带花园,带泳池的例子来实现一下装饰模式。
房屋抽象类
/**
* 房屋
* @author S
*
*/
public abstract class House {
public abstract String getDesc();
}
住宅实体类
/**
* 住宅
* @author S
*
*/
public class Flat extends House{
@Override
public String getDesc() {
// TODO Auto-generated method stub
return "住宅";
}
}
装饰者
/**
* 装饰者
* @author S
*
*/
public abstract class Decorator extends House{
public abstract String getDesc();
}
花园装饰
/**
* 花园装饰
* @author S
*
*/
public class GardenDecorator extends Decorator{
private House house;
public GardenDecorator(House house){
this.house = house;
}
@Override
public String getDesc() {
// TODO Auto-generated method stub
return "有花园的"+house.getDesc();
}
}
游泳池装饰
/**
* 游泳池装饰
* @author S
*
*/
public class SwimmingPoolDecorator extends Decorator{
private House house;
public SwimmingPoolDecorator(House house){
this.house = house;
}
@Override
public String getDesc() {
// TODO Auto-generated method stub
return "有泳池的"+house.getDesc();
}
}
Main
/**
* 设计模式之装饰者模式
*/
public class Main {
public static void main(String args[]){
//有花园有泳池
House house1 = new GardenDecorator(new SwimmingPoolDecorator(new Flat()));
//有花园
House house2 = new GardenDecorator(new Flat());
System.out.println(house1.getDesc());
System.out.println(house2.getDesc());
}
}
打印
有花园的有泳池的住宅
有花园的住宅