装饰者模式

来源:互联网 发布:光大证券金阳光mac版 编辑:程序博客网 时间:2024/06/07 17:41

定义:动态给一个对象添加一些额外的职责,Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。

设计初衷:通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。 装饰者模式比继承更有弹性,因为他是对象之间的关系,是动态的。

 要点:装饰者与被装饰者拥有共同的超类,继承的目的是继承类型,而不是行为


代码

  1. package Decorator;
  2. abstract class human {
  3. public abstract void show();
  4. }
  5. class person extends human{
  6. private String name;
  7. public person(String name) {
  8. this.name=name;
  9. }
  10. @Override
  11. public void show() {
  12. System.out.print("我是"+name+" 今天我要 ");
  13. }
  14. }
  15. abstract class Decorator extends human{
  16. private human human;
  17. public void Decorate(human human) {
  18. this.human=human;
  19. }
  20. @Override
  21. public void show(){
  22. human.show();
  23. }
  24. }
  25. class TShirts extends Decorator{
  26. public void show(){
  27. super.show();
  28. wereTShirts();
  29. }
  30. public void wereTShirts() {
  31. System.out.print("穿T恤 ");
  32. }
  33. }
  34. class Trouser extends Decorator{
  35. public void show(){
  36. super.show();
  37. wereTrouser();
  38. }
  39. public void wereTrouser() {
  40. System.out.print("穿裤衩 ");
  41. }
  42. }
  43. class Sneakers extends Decorator{
  44. public void show(){
  45. super.show();
  46. wereSneakers();
  47. }
  48. public void wereSneakers() {
  49. System.out.print("打领带 ");
  50. }
  51. // ......
  52. }
  1. package Decorator;
  2. public class Client {
  3. public static void main(String[]args){
  4. person person=new person("1e0zj");
  5. TShirts tShirts=new TShirts();
  6. Trouser trouser=new Trouser();
  7. Sneakers sneakers=new Sneakers();
  8. tShirts.Decorate(person);
  9. trouser.Decorate(tShirts);
  10. sneakers.Decorate(trouser);
  11. sneakers.show();
  12. }
  13. }
输出:我是1e0zj 今天我要 穿T恤 穿裤衩 打领带






原创粉丝点击