Loading

装饰设计模式

简介

装饰设计模式是指动态地给一个对象添加一些额外的功能,它的优点在于耦合性不强,被装饰类的变化与装饰类的变化无关。

示例

例如一个学生本来会javase和javaweb,但经过IT培训后学会了ssh,数据等,后面这些新增的功能就可以用装饰设计模式来实现。

public class Demo6_Wrap {

    public static void main(String[] args) {
        ItStudent hms = new ItStudent(new Student());
        hms.code();
    }

}

interface coder{
    public void code();
}

class Student implements coder{

    @Override
    public void code() {
        System.out.println("javase");
        System.out.println("javaweb");
    }

}

class ItStudent implements coder{
    // 1、获取被装饰类对象的引用
    private Student s;  // 获取学生引用

    // 2、在构造方法中传入被装饰类对象
    public ItStudent(Student s) {
        this.s = s;
    }

    // 对原有功能进行升级
    @Override
    public void code() {
        s.code();
        System.out.println("ssh");
        System.out.println("数据库");
        System.out.println("大数据");
        System.out.println("...");
    }

}
posted @ 2017-02-23 22:26  leon_x  阅读(38)  评论(0)    收藏  举报