zoukankan      html  css  js  c++  java
  • 设计模式一装饰者模式

    概述

       不改变其结构的情况下,可以动态地扩展其功能

       装饰者和被装饰者之间必须是一样的类型,也就是要有共同的超类

       这里应用继承并不是实现方法的复制,而是实现类型的匹配


    抽象构件(Component)角色:

    定义一个抽象接口以规范准备接收附加责任的对象。
    具体构件(Concrete Component)角色:
    实现抽象构件,通过装饰角色为其添加一些职责。
    抽象装饰(Decorator)角色:
    职责就是为了装饰我们的构件对象,内部一定要有一个指向构件对象的引用
    具体装饰(ConcreteDecorator)角色:
    实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
     1 //抽象构建
     2 interface Person {
     3     void eat();
     4 }
     5 
     6 //具体构建
     7 class Person_one implements Person {
     8 
     9     @Override
    10     public void eat() {
    11         System.out.println("吃大鱼");
    12     }
    13 }
    14 
    15 class Person_two implements Person {
    16 
    17     @Override
    18     public void eat() {
    19         System.out.println("吃小鱼");
    20     }
    21 }
    22 
    23 //抽象装饰者
    24 abstract class NewPerson implements Person {
    25     protected Person per;
    26 
    27     public NewPerson(Person per) {
    28         this.per = per;
    29     }
    30 
    31     public void eat() {
    32         per.eat();
    33     }
    34 }
    35 
    36 //具体装饰者
    37 class NewPerson_one extends NewPerson {
    38     public NewPerson_one(Person per) {
    39         super(per);
    40     }
    41 
    42     void dinner() {
    43         System.out.println("鲸鱼乱炖");
    44     }
    45 
    46     public void eat() {
    47         super.eat();
    48         dinner();
    49     }
    50 }
  • 相关阅读:
    angularjs学习笔记—工具方法
    js日期格式转换的相关问题探讨
    vue路由原理剖析
    如何减少UI设计师产品与前端工程师的沟通成本
    前端优化带来的思考,浅谈前端工程化
    前端入门方法
    自写juqery插件实现左右循环滚动效果图
    前端大综合
    前端收集
    如何在代码中减少if else语句的使用
  • 原文地址:https://www.cnblogs.com/loveer/p/11279219.html
Copyright © 2011-2022 走看看