特点:1,装饰类中包含被装饰类的引用。
2,不用修改被装饰类就能达到扩展功能。
优点:1,继承和装饰设计模式都能扩展功能,但是装饰模式更具灵活性。
缺点:1,设计更加复杂一些。
2,设计的时候会增加很多子类,过度使用装饰设计模式会使程序更加复杂。
下面是一个简单的例子:
步骤一:先定义一个接口,明确要做些什么功能。
public interface Eat { void eatNoodles(); }
步骤二:定义被装饰的类。
public class Person implements Eat{ private int age; private String name; public Person(int age,String name){ this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void eatNoodles(){ System.out.println(this.age+"岁的"+this.name+"在吃面条"); }
}
步骤三:开始装饰Person类。
public class NewPerson implements Eat{ private Person person; public NewPerson(Person person){ this.person = person; } public void eatNoodles(){ System.out.println("被装饰的"+person.getAge()+"岁的"+person.getName()+"在吃面条"); } }
步骤四:测试装饰设计模式。
public class DecorateDemo {
public static void main(String[] args) { // TODO Auto-generated method stub Person person = new Person(15, "小明"); NewPerson newPerson = new NewPerson(person); newPerson.eatNoodles(); }
}
输出结果:被装饰的15岁的小明在吃面条