装饰者模式
- 作用:动态的给一个对象添加额外功能
栗子:
拿武器来说:
- 武器Weapon(被装饰对象的基类)
- 武器有剑啦,斧头等(具体被装饰的对象)
- 装饰者抽象类Decorator
- 武器可以吸血,还有可以复活(具体装饰者)
*主要是在具体装饰者中要有Weapon(被装饰对象的基类)这个属性
看代码:
被装饰的基类Weapon
/*
* 被装饰的基类
* */
interface Weapon{
void show();
}
具体被装饰的对象(斧头)
/*
* 被装饰的具体对象(斧头)
* */
class Axe implements Weapon{
//武器的名字
String name;
//构造函数
public Axe(String name) {
this.name = name;
}
//实现接口的方法
public void show() {
System.out.println("我是"+name);
}
}
具体被装饰对象(剑)
/*
* 被装饰的具体对象(剑)
* */
class Sword implements Weapon{
//武器的名字
String name;
//构造函数
public Sword(String name) {
this.name = name;
}
//实现接口的方法
public void show() {
System.out.println("我是"+name);
}
}
装饰器
/*
* 装饰器
* */
abstract class Decorator implements Weapon{
//这里就不做什么了
}
具体装饰类(吸血)
/*
* 吸血
* */
class SuckBoold extends Decorator{
String type;
//主要是要有这个属性
Weapon weapon;
//构造函数
public SuckBoold(String type,Weapon weapon) {
this.type = type;
this.weapon = weapon;
}
public void show() {
System.out.println("我在"+type);
weapon.show();
}
}
具体装饰类(复活)
/*
* 复活功能
* */
class Resurgence extends Decorator{
String type;
//主要是要有这个属性
Weapon weapon;
//构造函数
public Resurgence(String type,Weapon weapon) {
this.type = type;
this.weapon = weapon;
}
public void show() {
System.out.println("我在"+type);
weapon.show();
}
}
测试类:
1,我要一把会吸血的剑
public static void main(String[] args) {
//吸血的剑
new SuckBoold("吸血", new Sword("绝世好贱")).show();
}
输出:
我在吸血
我是绝世好贱
2.复活的剑
public static void main(String[] args) {
//吸血的剑
new Resurgence("复活", new Sword("绝世好贱")).show();
}
输出:
我在复活
我是绝世好贱
3,我要一把会吸血又会复活的斧头
public static void main(String[] args) {
//吸血的剑
new Resurgence("复活", new SuckBoold("吸血", new Axe("多功能斧头"))).show();
}
输出:
我在复活
我在吸血
我是多功能斧头