public interface Component {
public void doThingA();
}
(2) 具体构件角色
package com.example.design.decorate;
public class ConcreteComponent implements Component {
@Override
public void doThingA() {
// TODO 自动生成的方法存根
System.out.println("具体构件实现的抽象接口,do thing A ");
}
}
(3) 装饰类角色
package com.example.design.decorate;
public class Decorator implements Component{
private Component component = null;
public Decorator(Component component) {
this.component = component;
}
@Override
public void doThingA() {
// TODO 自动生成的方法存根
component.doThingA();//使用时调用被装饰对象的方法
}
}
(4) 具体装饰角色
具体装饰角色1
package com.example.design.decorate;
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component) {
super(component);// 调用父类的构造方法
}
@Override
public void doThingA() {
// TODO 自动生成的方法存根
super.doThingA();//调用被包装类的方法
doThingB();//“附加”功能
}
//要添加的扩展的功能
public void doThingB(){
System.out.println("具体装饰模式 do thing B");
}
}
具体装饰角色2
package com.example.design.decorate;
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component) {
super(component);
}
@Override
public void doThingA() {
// TODO 自动生成的方法存根
super.doThingA();//调用被包装类的方法
doThingC();
}
//扩展的功能
public void doThingC(){
System.out.println("具体装饰模式 do thing C");
}
}
最后是测试类
public class TestMain {
public static void main(String[] args) {
// TODO 自动生成的方法存根
ConcreteComponent concretecomponent =new ConcreteComponent();
concretecomponent.doThingA();
System.out.println("---------");
//装饰包装一层
ConcreteDecorator1 concreteDecorator1=new ConcreteDecorator1(concretecomponent);
concreteDecorator1.doThingA();
System.out.println("---------");
最后
金三银四马上就到了,希望大家能好好学习一下这些技术点
学习视频:
大厂面试真题:
concreteDecorator1.doThingA();
System.out.println("---------");
最后
金三银四马上就到了,希望大家能好好学习一下这些技术点
学习视频:
[外链图片转存中…(img-viG2p55N-1714385059674)]
大厂面试真题:
[外链图片转存中…(img-mAaVd3JB-1714385059675)]