设计模式是编程的通用技术,略微学习了一下其中的装饰设计模式
装饰设计模式的步骤简单分为以下几步:
1.获取被装饰类的引用
2.在构造方法中传入被装饰的对象
3.对原有功能进行升级
代码如下:
interface Coder{
public void code();
}
class Student implements Coder{
public void code(){
System.out.println("原有功能");
System.out.println("原有功能");
}
}
被装饰的类是Student,现在新建一个类NewStudent
对其装饰:
class NewStudent implements Coder{
private Student s; //获取学生引用
//构造函数传入被装饰的对象
public NewStudent(Student s){
this.s = s;
}
@Override
public void code() {
// TODO Auto-generated method stub
s.code();//已有的功能
System.out.println("新增的功能");
System.out.println("新增的功能");
}
}
装饰设计模式的好处是减少耦合性,无需继承,能动态地为一个类添加功能,使用对象的关联关系代替继承关系,更加灵活,经典使用场景是IO中的输入跟输出流