zoukankan      html  css  js  c++  java
  • 装饰模式

    装饰模式的定义:

      装饰模式是用来替代继承的一种设计模式。它通过一种无须定义子类的方式来给对象动态增加职责,使用对象之间的关联关系取代类之间的继承关系。降低了系统的耦合,可以动态的增加或者删除对象的职责。

    装饰模式的结构

      装饰模式主要包含以下角色。

      1. 抽象构件Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
      2. 具体构件Concrete    Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
      3. 抽象装饰Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
      4. 具体装饰ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

    装饰模式的具体实现

    package decorator;
    public class DecoratorPattern
    {
        public static void main(String[] args)
        {
            Component p=new ConcreteComponent();
            p.operation();
            System.out.println("---------------------------------");
            Component d=new ConcreteDecorator(p);
            d.operation();
        }
    }
    //抽象构件角色
    interface  Component
    {
        public void operation();
    }
    //具体构件角色
    class ConcreteComponent implements Component
    {
        public ConcreteComponent()
        {
            System.out.println("创建具体构件角色");       
        }   
        public void operation()
        {
            System.out.println("调用具体构件角色的方法operation()");           
        }
    }
    //抽象装饰角色
    class Decorator implements Component
    {
        private Component component;   
        public Decorator(Component component)
        {
            this.component=component;
        }   
        public void operation()
        {
            component.operation();
        }
    }
    //具体装饰角色
    class ConcreteDecorator extends Decorator
    {
        public ConcreteDecorator(Component component)
        {
            super(component);
        }   
        public void operation()
        {
            super.operation();
            addedFunction();
        }
        public void addedFunction()
        {
            System.out.println("为具体构件角色增加额外的功能addedFunction()");           
        }
    }

      缺点:

        在使用装饰模式的时候进行系统设计时会产生很多小对象,这些对象的区别在于们之间相互连接的方式有所不同而不是他们的类或者属性值有所不同大量小对象势必产生一大部分的系统资源开销。影响系统性能

  • 相关阅读:
    Android开发
    Android随笔
    Android开发
    宁波大学NBU计算机大三下册期末考试
    2021浙江省大学生程序设计竞赛D题 Shortest Path Query(最短路+思维)
    NWERC 2020A Atomic Energy(背包+思维)
    CF1454E Number of Simple Paths(容斥+基环树)
    CF549F(分治+启发式合并)
    HDU5293 Tree chain problem (LCA+树链剖分+线段树)
    HDU156 The more, The Better(dp+背包)
  • 原文地址:https://www.cnblogs.com/JonaLin/p/12718617.html
Copyright © 2011-2022 走看看