装饰模式
作者:互联网
装饰模式
装饰模式:IO设计的核心思想,在不影响原有对象的前提下,无侵入的给一个对象增加一些额外的功能。
代码:
先写一个接口
public interface Phone {
public void call();
}
再写一个接口实现类:
public class ConcretePhone implements Phone{
@Override
public void call() {
System.out.println("打电话");
}
}
抽象方法:
public abstract class SmartPhone implements Phone{
private Phone phone;
public SmartPhone(Phone phone){
this.phone = phone;
phone.call();
}
@Override
public void call() {
}
}
SmartPhone的子类一:
public class ConcreteSmartPhone1 extends SmartPhone {
private Phone phone;
public ConcreteSmartPhone1(Phone phone) {
super(phone);
}
public void call(){
super.call();
changgecolor();
}
public void changgecolor(){
System.out.println("改变颜色");
}
}
SmartPhone的子类二:
public class ConcreteSmartPhone2 extends SmartPhone{
public ConcreteSmartPhone2(Phone phone) {
super(phone);
}
public void call(){
super.call();
changgesize();
}
public void changgesize(){
System.out.println("改变大小");
}
}
测试类:
public class Test {
public static void main(String[] args) {
ConcretePhone p = new ConcretePhone();
ConcreteSmartPhone1 s1 = new ConcreteSmartPhone1(p);
s1.call();
System.out.println("------");
SmartPhone s = new ConcreteSmartPhone2(new ConcreteSmartPhone1(p));
s.call();
}
}
结果为:
标签:SmartPhone,phone,void,模式,public,Phone,call,装饰 来源: https://blog.csdn.net/weixin_43891499/article/details/115116111