Design Pattern:
Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. 模式:装饰器模式允许类上添加新功能并且不改变原有的状态,属于结构性模式
故事场景:不是创建这个类的子类,而是implements实现被装饰类的接口,然后 引用被装饰类方法,并且加上自己另外实现的方法(继承比组合更加膨胀)
Player
public interface Player {
void play();
}
public class Curry implements Player {
@Override
public void play() {
System.out.println("Curry 远投3分");
}
}
PlayerDecorator装饰器
public class PlayerDecorator implements Player {
protected Player player;
public PlayerDecorator(Player player){
this.player = player;
}
@Override
public void play() {
player.play();
dunk();
}
public void dunk(){
System.out.println("顺便又暴扣2分");
}
}
实验的开始
public class DecoratorDemo {
public static void main(String[] args) {
Player curry = new Curry();
Player player = new PlayerDecorator(curry);
player.play();
}
}
结果
