常见的结构型模式:
一、装饰者模式介绍
1.1、装饰者模式定义
装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案
1.2、装饰者模式中类或者接口的作用
- 抽象构建角色:给出一个抽象接口,以规范准备接收附加责任的对象
- 具体构建角色:定义一个将要接收附加责任的类
- 装饰角色:持有一个构建对象的实例,并定义一个与抽象构建接口一致的接口
- 具体装饰角色:负责给构建对象“贴上附加责任”
1.3、为什么使用装饰者而不使用继承?
装饰模式可以提供比继承更多的灵活性。装饰模式允许动态增加或者删除一个装饰的功能,继承需要在此之前就要确定好对应的类
二、示例介绍
示例1:模拟穿衣服场景
每个人一天起床之后都要穿衣服(来装饰自己),这是必不可少的,这样问题就来了,穿什么?按照什么顺序穿?如何用程序方便的模拟这个场景?
/**
* 程序模拟一个人穿衣服的过程
* @author: qhyuan1992
*/
// 抽象接口,用来规范将要被附加一些操作的对象
interface People{
public void wear();
}
// 具体的对象,该对象将被附加一些额外的操作
class Jane implements People{
public void wear() {
System.out.println("今天该穿什么呢?");
}
}
// 装饰者类,持有一个将要被装饰的接口对象的实例
class Decorator implements People{
private People people;
public Decorator(People people) {
this.people = people;
}
public void wear() {
people.wear();
}
}
// 具体的装饰者类,负责给增加附加的操作:穿衬衫
class DecoratorShirt extends Decorator{
public DecoratorShirt(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个衬衫");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿西服
class DecoratorSuit extends Decorator{
public DecoratorSuit(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个西服");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿T-Shirt
class DecoratorTShirt extends Decorator{
public DecoratorTShirt(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个T-Shirt");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿裤子
class DecoratorPants extends Decorator{
public DecoratorPants(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿裤子");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿鞋子
class DecoratorShoes extends Decorator{
public DecoratorShoes(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("鞋子");
}
}
public class DecoratorTest {
public static void main(String[] args) {
People p1 = new DecoratorSuit(new DecoratorShirt(new Jane()));
p1.wear();
System.out.println("--------------");
People p2 = new DecoratorTShirt(new DecoratorPants(new Jane()));
p2.wear();
System.out.println("--------------");
People p3 = new DecoratorTShirt(new DecoratorPants(new DecoratorShoes(new Jane())));
p3.wear();
System.out.println("--------------");
People p4 = new DecoratorShoes(new DecoratorPants(new DecoratorTShirt(new Jane())));
p4.wear();
}
}
/**
在上面的穿衣服的例子里面:
People类:抽象接口,用来规范将要被附加一些操作的对象
Jane类:具体的对象,该对象将被附加一些额外的操作
Decorator类: 装饰者类,持有一个将要被装饰的接口对象的实例
DecoratorShirt类:具体的装饰者类,负责给增加附加的操作:穿衬衫
DecoratorSuit类:具体的装饰者类,负责给增加附加的操作:穿西服
DecoratorTShirt类:具体的装饰者类,负责给增加附加的操作:穿T-Shirt
DecoratorPants类:具体的装饰者类,负责给增加附加的操作:穿裤子
DecoratorShoes类:具体的装饰者类,负责给增加附加的操作:穿鞋子
**/
打印输出:
今天该穿什么呢?
穿个衬衫
穿个西服
————–
今天该穿什么呢?
穿裤子
穿个T-Shirt
————–
今天该穿什么呢?
鞋子
穿裤子
穿个T-Shirt
————–
今天该穿什么呢?
穿个T-Shirt
穿裤子
鞋子