package cn.itcast.decorator;
public class DecoratorDemo {
public static void main(String[] args) {
Person p = new Person();
p.eat();
}
}
class Person{
public void eat() {
System.out.println("我正在吃···········");
}
}
首先我们有了人这个类,创建了他的对象,然后人是需要吃饭的,但是吃饭之前他需要先吃一点甜点。但是这回人的对象p已经创建出来了。之中并没有先吃甜点的方法。这个时候如果我们是用继承,创建一个他的子类。拓展它的功能,显然非常的不合适。于是便有了下面一个巧妙的解决方法。
package cn.itcast.decorator;
public class DecoratorDemo {
/**
* 装饰设计模式
* 解决的问题是:给已有的对象提供额外增强的功能。还不对原有对象进行修改
* 对对象而言是透明的 就像什么都没有发生过一样
* @param args
*/
public static void main(String[] args) {
Person p = new Person();
SuperPerson sp = new SuperPerson(p);
sp.eat();
}
}
class Person{
public void eat() {
System.out.println("我正在吃···········");
}
}
class SuperPerson{
private Person p;
public SuperPerson(Person p) {
this.p = p;
}
public void eat() {
System.out.println("先吃点甜点");
p.eat();
}
}
这就是装饰设计模式,java的IO流中大量的用到了这个模式。