最早接触装饰模式是在学I/O的时候,当时老师讲过Buffer系列的输入输出流就是用到了装饰模式,我对装饰模式的理解就是在实现类的基础上对其进一步的增强(区别于扩展)就是装饰模式的核心理念,例如有下面场景
例如给房子装修添置家具可能有多种不同的变化,每种变化占用的房屋面积和花销肯定也会不一样,那怎么才能能灵活的体现出每添置一样家具后房屋的可用面积和花销的变化呢,接下来用装饰模式的思想实现一下代码
首先看一下装饰模式的设计类
- 抽象组件:需要装饰的抽象对象
- 具体组件:是我们需要装饰的对象
- 抽象装饰类:内含指向抽象组件的引用及装饰者共有的方法
- 具体装饰类:被装饰的对象
先设计抽象组件,也就是房子的设计原型,我们这里只关注房子的可用面积和花销
public interface House {
Integer area(); //可用面积
Integer cost(); //花销
}
接下来设计具体组件,也就是造好这栋房子,为了方便后面看效果都写成整型
public class BuildHouse implements House {
@Override
public Integer area() {
return 100;
}
@Override
public Integer cost() {
return 1000000;
}
}
然后是抽象装饰类,也就是家具类,因为家具是用来装饰房子的,所以在构造时就要传入房子对象
public abstract class Furniture implements House {
protected House house;
public Furniture(House myHouse) {
this.house = myHouse;
}
public Integer area() {
return house.area();
}
public Integer cost() {
return house.cost();
}
}
最后是家具类的具体实现,我们这里以床、桌子和沙发为例
public class Sofa extends Furniture {
public Sofa(House house) {
super(house);
}
//添置家具后当前房子可用面积变小
public Integer area() {
return super.area() - 3;
}
public Integer cost() {
return super.cost() + 5000;
}
}
public class Bed extends Furniture {
public Bed(House house) {
super(house);
}
public Integer area() {
return super.area() - 4;
}
public Integer cost() {
return super.cost() + 10000;
}
}
public class Desk extends Furniture {
public Desk(House house) {
super(house);
}
public Integer area() {
return super.area() - 1;
}
public Integer cost() {
return super.cost() + 1000;
}
}
好了,基本的房子框架已经构建完成,接下来测试一下
public class MyHouse {
public static void main(String[] args) {
System.out.println("=========建造房子==========");
House house = new BuildHouse();
System.out.println("可用面积: "+ house.area() + ", 花销: " + house.cost());
//往房子添置家具
System.out.println("=========添置家具==========");
house = new Sofa(house);
System.out.println("添置沙发后--> 可用面积: "+ house.area() + ", 花销: " + house.cost());
house = new Bed(house);
System.out.println("添置床--> 可用面积: "+ house.area() + ", 花销: " + house.cost());
house = new Desk(house);
System.out.println("添置桌子--> 可用面积: "+ house.area() + ", 花销: " + house.cost());
}
}
输出结果
=========建造房子==========
可用面积: 100, 花销: 1000000
=========添加家具==========
添置沙发后--> 可用面积: 97, 花销: 1005000
添置床--> 可用面积: 93, 花销: 1015000
添置桌子--> 可用面积: 92, 花销: 1016000
装饰模式基本概念大概就是这样,其最核心的功能就是对类的增强
本文通过一个具体的例子详细介绍了装饰模式的概念及其应用。通过为房子添置不同家具来展示如何使用装饰模式来灵活地增加对象的功能。
683

被折叠的 条评论
为什么被折叠?



