Decorator模式,装饰者模式
具有相应功能的代码 = 光秃秃的房子,把房子造好了,接下去当然是要装修了。Decorator模式,顾名思义,就是美化我们的输出了。
- 比如房子里有客厅,卧室,厨房,你有分别要加入什么家具,这些家具就可以使用Decorator模式
- 还有比如吃火锅的时候,加入锅底以外的东西时,也可以使用Decorator模式,=>吃各种东西都可以
- 还有相机的各种P图功能,哈哈哈哈
场景模拟和一般通用格式
那咱就来喝杯奶茶吧
基地:牛奶,红茶,绿茶
配料:红豆,仙草,珍珠,青稞,奶盖,芋圆
component:
package decorator模式;
public class component {
protected String name;
public String getName() {
return this.name;
}
}
concreteComponent:
package decorator模式;
public class concreteComponent extends component{
public concreteComponent() {
this.name = "milktea";
}
}
decorator:
package decorator模式;
public abstract class decorator extends component{
public abstract String getName();
public void putout() {
System.out.println(getName());
}
}
concreteDecorator:
package decorator模式;
public class concreteDecorator extends decorator{
private component milktea;
public concreteDecorator(component milktea) {
this.milktea = milktea;
}
@Override
public String getName() {
return milktea.getName() + ":" + " add red beans ";
}
}
concreteDecorator:第二种装饰,即不同种类的加料
package decorator模式;
public class concreteDecoratorTwo extends decorator{
private component milktea;
public concreteDecoratorTwo(component milktea) {
this.milktea = milktea;
}
@Override
public String getName() {
return milktea.getName()+" add pearls";
}
}
main:
package decorator模式;
public class main {
public static void main(String[] args) {
component result = new concreteComponent();
decorator redBeens = new concreteDecorator(result);
redBeens.putout();//红豆牛奶
decorator pearls = new concreteDecoratorTwo(redBeens);
pearls.putout();//红豆珍珠牛奶
}
}
自己可以根据需求修改配料哦,快去搭配你的奶茶吧
再看定义
官方:动态地给对象附加职责。
普通:给对象进行一层包装。
要点: 装饰者与被装饰者拥有共同的超类,继承的目的是继承类型,而不是行为
增加或减少功能时,对底层代码修改少
重要角色
- 抽象组件(Component) :定义规范
- 被装饰者(ConcreteComponent) :Component的具体实现,也就是我们要装饰的具体对象
- 装饰者组件(Decorator) :持有组件(Component)对象的实例引用,该类的职责就是为了装饰具体组件对象,定义的规范。
- 具体装饰(ConcreteDecorator) :加功能的地方
优缺点
优点:
- 可以对一个对象进行多次修饰,创造出不同的行为组合,得到功能更为强大的对象
- 具体组件类和具体装饰类可以独立变化,使用者根据需求可以自己组合
- 比继承灵活,不会导致类个数急剧增加,(面向对象设计原则:多组合,少继承)
缺点:
- 产生很多小对象。大量小对象占据内存,一定程度上影响性能
- 容易出错,不易排查
- 装饰链过长时,会影响效率
今天入门小白的学习就到这里啦,如果不正之处,欢迎指正!万分感谢!
参考教材:《图解设计模式》
主要参考博客: