现象:
设计模式-结构型设计模式-装饰模式学习
动态的给对象添加新的功能
装饰模式可以在不改变一个对象本身的基础上给对象增加额外的新行为
方法:
1:抽象构建角色
/**
* 抽象构建角色 哥斯拉
*/
public interface Component {
public void show();
}
2:具体实现
/**
* 具体构件 ConcreteComponent角色 普通哥斯拉
*/
public class ConcreteComponent implements Component{
private String color="灰色(普通)";
@Override
public void show() {
System.out.println("展示哥斯拉:"+color);
}
public void setColor(String color) {
this.color = color;
}
}
3:抽象装饰角色
/**
* 抽象装饰角色-哥斯拉变形
*/
public class Decorator implements Component{
Component component;
public Decorator(Component component){
this.component=component;
}
@Override
public void show() {
component.show();
}
}
4:具体装饰角色
/**
* 具体装饰角色:红莲哥斯拉
*/
public class ConcreteDecorator extends Decorator{
public ConcreteDecorator(Component component) {
super(component);
}
public void show(){
addFunction();
super.show();
}
public void addFunction(){
System.out.println("装饰器-增强");
((ConcreteComponent)super.component).setColor("红色(红莲)");
}
}
5:使用
普通哥斯拉出现
ConcreteComponent concreteComponent = new ConcreteComponent();
concreteComponent.show();
//展示哥斯拉:灰色(普通)
普通哥斯拉变形之后
ConcreteDecorator concreteDecorator = new ConcreteDecorator(new ConcreteComponent());
concreteDecorator.show();
// 展示哥斯拉:红色(红莲)
6:代理模式与装饰模式
装饰模式是对本身的增强 ,代理模式是新的代理对象
代理模式
public class Proxy implements House {
private House house;
public Decorator(){
this.house = new DonghaoHouse();
}
@Override
public void output() {
System.out.println("这是针对目标的前段增强");
house.output();
System.out.println("这是针对目标的后段增强");
}
}
装饰模式
public class Decorator implements House {
private House house;
public Decorator(House house){
this.house = house;
}
@Override
public void output() {
System.out.println("这是针对房子的前段装饰增强");
house.output();
System.out.println("这是针对房子的后段装饰增强");
}
}