装饰者模式简述
- 装饰者模式可以形象的比喻一所大房子,外面只有一个门.打开门里面还有门.打开门获取一点金钱.你可以无限的进门..
- Component(被装饰对象的基类)
- ConcreteComponent(具体被装饰对象)
- Decorator(装饰者抽象类)
- ConcreteDecorator(具体装饰者)
类图
代码
定义一个抽象类(非必须)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package com.pan.component;
/**
* 抽象类
*
* @author xinyi.pan
*
*/
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}定义一个被装饰的接口(定义公共的方法).
1
2
3
4
5
6
7
8package com.pan.component;
public interface Fight {
//公共方法(门)
public String fightPower() ;
}单独类cat
1
2
3
4
5
6
7
8
9
10
11
12
13package com.pan.component;
public class Cat extends Animal implements Fight {
public Cat(String name) {
super(name);
}
//基类的门,里面不再有门..
public String fightPower() {
return super.getName() +" fighting" ;
}
}单独类cattle
1
2
3
4
5
6
7
8
9
10
11
12package com.pan.component;
public class Cattle extends Animal implements Fight {
public Cattle(String name) {
super(name);
}
public String fightPower() {
return super.getName() + " sleep";
}
}定义抽象装饰类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package com.pan.decorator;
import com.pan.component.Fight;
public abstract class AnimalDecorator implements Fight {
private Fight fight;
// 构造函数添加被装饰着对象
public AnimalDecorator(Fight fight) {
this.fight = fight;
}
//拆包装饰者
public String fightPower() {
//调用装饰者公共方法
doDecoratorFight();
//打开下一个门
return fight.fightPower();
}
//装饰者的公共方法.
public abstract void doDecoratorFight() ;
}cattle装饰类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package com.pan.decorator;
import com.pan.component.Fight;
public class CattleDecorator extends AnimalDecorator {
public CattleDecorator(Fight fight) {
super(fight);
}
@Override
public String fightPower() {
return super.fightPower();
}
@Override
public void doDecoratorFight() {
System.out.println("cattle 打豆豆");
}
}测试方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package com.pan.test;
import com.pan.component.Cat;
import com.pan.decorator.CatDecorator;
import com.pan.decorator.CattleDecorator;
public class CalTest {
public static void main(String[] args) {
System.out.println("==================未装饰cat==================");
System.out.println(new Cat("cat").fightPower());
System.out.println("===================装饰cat======================");
CatDecorator catDecorator = new CatDecorator(new Cat("cat")) ;
System.out.println(catDecorator.fightPower());
CattleDecorator cattleDecorator = new CattleDecorator(catDecorator) ;
System.out.println("====================cattle装饰cat装饰=====================");
System.out.println(cattleDecorator.fightPower());
}
}结果
1
2
3
4
5
6
7
8
9==================未装饰cat==================
cat fighting
===================装饰cat======================
cat 打豆豆
cat fighting
====================cattle装饰cat装饰=====================
cattle 打豆豆
cat 打豆豆
cat fighting