一.作用:动态的给一个对象添加额外的功能。
二.代码
1.被装饰的接口Person
1 package design.decorator; 2 3 public interface Person { 4 void eat(); 5 }
2.Person接口的多种实现Man和Woman
1 package design.decorator; 2 3 public class Man implements Person{ 4 5 @Override 6 public void eat() { 7 // TODO Auto-generated method stub 8 System.out.println("一个男人在吃饭..."); 9 } 10 11 }
1 package design.decorator; 2 3 public class Woman implements Person{ 4 5 @Override 6 public void eat() { 7 // TODO Auto-generated method stub 8 System.out.println("一个女人在吃饭..."); 9 } 10 11 }
3.抽象的装饰器类Decorator来装饰接口Person,这样的话不同的装饰器抽象类的实现类就可以装饰任意Person接口的实现类
1 package design.decorator; 2 3 public abstract class Decorator implements Person { 4 private Person person; 5 public void setPerson(Person person){ 6 this.person = person; 7 } 8 9 public void eat(){ 10 person.eat(); 11 } 12 }
3.抽象装饰器类A和B
1 package design.decorator; 2 3 public class PersonDecoratorA extends Decorator{ 4 5 public void eat(){ 6 washHand(); 7 super.eat(); 8 washHand(); 9 } 10 11 public void washHand(){ 12 System.out.println("洗手。。"); 13 } 14 }
1 package design.decorator; 2 3 public class PersonDecoratorB extends Decorator{ 4 public void eat(){ 5 stealEat(); 6 super.eat(); 7 } 8 9 public void stealEat(){ 10 System.out.println("偷吃。。"); 11 } 12 }
4.测试:用装饰器A装饰Woman,装饰器B装饰Man
1 package design.decorator; 2 3 public class Test { 4 public static void main(String[] args) { 5 Man man = new Man(); 6 Woman woman = new Woman(); 7 PersonDecoratorA mda = new PersonDecoratorA(); 8 PersonDecoratorB mdb = new PersonDecoratorB(); 9 mda.setPerson(woman); 10 mda.eat(); 11 System.out.println("-------------------------"); 12 mdb.setPerson(man); 13 mdb.eat(); 14 } 15 }
5.结果
洗手。。
一个女人在吃饭...
洗手。。
-------------------------
偷吃。。
一个男人在吃饭...