JAVA 装饰者设计模式案例
装饰者模式的目的:在不修改原有类代码基础上,对原来代码进行增强,符合开闭原则
实现步骤:
1. 装饰者和被装饰者都实现共同的接口
2. 装饰者内部保存被装饰者的对象
3. 创建装饰者的时候传入被装饰者对象
4. 调用装饰者方法时,会调用被装饰者方法,同时进行增强
补充:AOP代理模式和装饰者模式的区别是:代理模式倾向于访问的控制,装饰模式倾向于功能的增强
1.定义接口
//战斗接口
public interface Fight {
void attack();
void move();
}
2.被装饰者实体类
//普通人
public class Man implements Fight {
@Override
public void attack() {
System.out.println("拳打脚踢");
}
@Override
public void move() {
System.out.println("拼命跑");
}
}
3.装饰者实体类
public class FightCloth implements Fight {
//普通人对象
private Fight man = null;
//创建时传入被装饰对象
public FightCloth(Fight man) {
this.man = man;
}
@Override
public void attack() {
//调用被装饰对象的方法
this.man.attack();
//增强
System.out.println("发射激光炮");
}
@Override
public void move() {
this.man.move();
System.out.println("飞起来了");
}
}
4.测试类
public class FightTest {
public static void main(String[] args) {
//被装饰对象
Fight man = new Man();
man.attack();
man.move();
System.out.println("-----------");
//穿战衣
Fight fightCloth = new FightCloth(man);
fightCloth.attack();
fightCloth.move();
}
}