• 装饰模式


    装饰模式
    装饰模式(Decorator),动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

     示图代码如下:

    1 public abstract class Component {
    2     public abstract void operation();
    3 }
    Component
    1 public class ConcreteComponent extends Component {
    2 
    3     @Override
    4     public void operation() {
    5         System.out.println("具体对象的操作");
    6     }
    7 
    8 }
    ConcreteComponent
     1 public abstract class Decorator extends Component {
     2     protected Component component;
     3     
     4     public Component getComponent() {
     5         return component;
     6     }
     7 
     8     public void setComponent(Component component) {
     9         this.component = component;
    10     }
    11 
    12     @Override
    13     public void operation() {
    14         if(component!=null){
    15             component.operation();
    16         }
    17 
    18     }
    19 
    20 }
    Decorator
     1 public class ConcreteDecoratorA extends Decorator {
     2     String addedState;
     3     @Override
     4     public void operation() {
     5         super.operation();
     6         addedState = "New State";
     7         System.out.println("具体装饰对象A的操作");
     8     }
     9 
    10 }
    ConcreteDecoratorA
     1 public class ConcreteDecoratorB extends Decorator {
     2 
     3     @Override
     4     public void operation() {
     5         super.operation();
     6         addedBehavior();
     7         System.out.println("具体装饰对象B的操作");
     8     }
     9     
    10     private void addedBehavior(){
    11         System.out.println("--咕噜噜---");
    12     }
    13 }
    ConcreteDecoratorB
     1 public class TestDecorator {
     2     public static void main(String[] args) {
     3         ConcreteComponent con = new ConcreteComponent();
     4         ConcreteDecoratorA d1 = new ConcreteDecoratorA();
     5         ConcreteDecoratorB d2 = new ConcreteDecoratorB();
     6         
     7         d1.setComponent(con);
     8         d2.setComponent(d1);
     9         d2.operation();
    10         
    11     }
    12 }
    test
    具体对象的操作
    具体装饰对象A的操作
    --咕噜噜---
    具体装饰对象B的操作
    测试打印

    装饰模式利用setComponent来对对象进行包装的,这样每个装饰对象实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,就不需要关心如何被添加到队形链当中
    如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

  • 相关阅读:
    最全的静态网站生成器(开源项目)
    移动互联网流量变现模式调研问卷
    公众平台商户接入(微信支付)功能申请教程
    微信支付全面开放
    百度天气预报接口
    微信公众平台开发(83) 生成带参数二维码
    微信支付接口申请指南
    微信自媒体账号涉违规大规模被封
    php大文件上传解决方案支持分片断点上传
    html5大文件上传解决方案(500M以上)
  • 原文地址:https://www.cnblogs.com/cai170221/p/13446105.html
Copyright © 2020-2023  润新知