装饰器模式:动态的给对象添加新的功能。
主要有以下几种角色:
ConcreteCompnent(具体构件):作为需要被装饰的类,在具体构件中只需要实现最基础的业务逻辑即可;
Decorator(抽象装饰器):抽象装饰器维护了一个指向抽象构件对象的引用(子类通过构造器等方法明确使用何种具体构件),即通过组合方式将装饰者和被装饰者建立起一个相比继承关系更为宽松的联系。同时作为抽象构件的子类,抽象装饰器还给具体构件增加了额外的职责,其额外的职责在抽象装饰器的子类中得到实现;
ConcreteDecorator(具体装饰器):作为抽象装饰器的子类,具体装饰器实现了需要给具体构件添加的额外职责;
Component(抽象构件):需要被装饰类的基类,同时也是装饰者的基类,在这个基类中声明了需要实现的业务方法
1、优点
(1)装饰类和被装饰类可以独立发展,而不会相互耦合。换句话说,Component类无需知道Decorator类,Decorator类是从外部来扩展Component类的功能,而Decorator也不用知道具体的构件。
(2)装饰器模式是继承关系的一个替代方案。我们看装饰类Decorator,不管装饰多少层,返回的对象还是Component(因为Decorator本身就是继承自Component的),实现的还是is-a的关系。
2、缺点
(1)装饰器模式虽然减少了类的爆炸,但是在使用的时候,你就可能需要更多的对象来表示继承关系中的一个对象
(2)装饰器模式虽然从数量级上减少了类的数量,但是为了要装饰,仍旧会增加很多的小类这些具体的装饰类的逻辑将不会非常的清晰,不够直观,容易令人迷惑。
示例
Component(抽象构件):
public interface Product {
void fuction();
}
ConcreteCompnent(具体构件):
public class Phone implements Product{
@Override
public void fuction() {
System.out.println("手机能拍照");
}
}
Decorator(抽象装饰器):
public abstract class PhoneDecorator implements Product {
private Product product;
public PhoneDecorator(Product product) {
this.product = product;
}
@Override
public void fuction() {
this.product.fuction();
}
}
ConcreteDecorator(具体装饰器):
public class PhoneDecoratorInfo extends PhoneDecorator{
public PhoneDecoratorInfo(Product product) {
super(product);
}
@Override
public void fuction() {
super.fuction();
System.out.println("添加短信功能");
}
}
public class PhoneDecoratorInfo1 extends PhoneDecorator{
public PhoneDecoratorInfo1(Product product) {
super(product);
}
@Override
public void fuction() {
super.fuction();
System.out.println("添加一个打电话功能");
}
}
测试:文章来源:https://www.toymoban.com/news/detail-408252.html
public class Test {
public static void main(String[] args) {
Product product=new Phone();
PhoneDecoratorInfo phoneDecoratorInfo = new PhoneDecoratorInfo(product);
PhoneDecoratorInfo phoneDecoratorInfo1=new PhoneDecoratorInfo(new PhoneDecoratorInfo1(new PhoneDecoratorInfo1(phoneDecoratorInfo)));
phoneDecoratorInfo1.fuction();
}
}
结果:文章来源地址https://www.toymoban.com/news/detail-408252.html
到了这里,关于装饰器模式(结构性)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!