gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)
介绍下设计模式的装饰者模式
- User
介绍下设计模式的装饰者模式
- Assistant
装饰者模式属于结构型设计模式,其可以在不改变原有类的情况下,对其进行功能扩展和增强。
装饰者模式的实现方式是:创建一个包装类,用于包装原有类,并在包装类中添加新的功能。通过包装类的接口调用,在原有类执行业务逻辑前或后,执行新添加的功能。
装饰者模式中的角色包括:
-
抽象组件(Component):定义原有类和包装类的共同接口,即被包装对象和包装器都必须实现的接口。
-
具体组件(ConcreteComponent):是被包装的原有类。
-
抽象装饰器(Decorator):包含一个指向抽象组件的引用并实现共同接口。其内部可以包含其它装饰器对象,可以在原有功能的基础上添加一些新的功能。
-
具体装饰器(ConcreteDecorator):实现包装类的具体功能。
在使用装饰者模式时,可以通过组合的方式,动态组合不同的装饰器对象来达到不同的功能扩展目的,实现代码的可复用性和可扩展性。
示例代码如下:
// 抽象组件 public interface Component { void operation(); // 原有类方法 } // 具体组件 public class ConcreteComponent implements Component { @Override public void operation() { System.out.println("执行原有类方法"); } } // 抽象装饰器 public abstract class Decorator implements Component { protected Component component; public Decorator(Component component) { this.component = component; } @Override public void operation() { component.operation(); } } // 具体装饰器1 public class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(Component component) { super(component); } @Override public void operation() { super.operation(); addedBehavior(); } public void addedBehavior() { System.out.println("添加的装饰器1功能"); } } // 具体装饰器2 public class ConcreteDecorator2 extends Decorator { public ConcreteDecorator2(Component component) { super(component); } @Override public void operation() { super.operation(); addedBehavior(); } public void addedBehavior() { System.out.println("添加的装饰器2功能"); } } // 客户端调用 public class Client { public static void main(String[] args) { // 创建具体组件 Component component = new ConcreteComponent(); // 添加装饰器1 component = new ConcreteDecorator1(component); // 添加装饰器2 component = new ConcreteDecorator2(component); // 执行方法,输出结果 component.operation(); } }运行结果为:
执行原有类方法 添加的装饰器1功能 添加的装饰器2功能 -