• Java装饰模式


    首先,直接代码说话

      

    //广阔的空间里,到处都是美好的气息
    interface
    BroadItch{ void getItch(); }
    //我们可以直接去个好地方
    class Library implements BroadItch{ @Override public void getItch() { System.out.println("图书馆看书好舒服!"); } }
    //也可以创造个工具,帮我们导引去找个地方
    class HomeBuilder implements BroadItch{ private BroadItch broadItch;//保持对抽象的引用 public HomeBuilder(BroadItch broadItch) { this.broadItch = broadItch; } public void getItch() { broadItch.getItch(); } }
    //用工具去找个学校
    class School extends HomeBuilder{ public School(BroadItch broadItch) { super(broadItch); } @Override public void getItch() { System.out.println("早个学校"); } }
    //或者去找个地方做礼拜
    class Temple extends HomeBuilder { public Temple(BroadItch broadItch) { super(broadItch); } @Override public void getItch() { System.out.println("做礼拜去!"); } }
    /**
     * Created by nicknailo on 2018/4/14.
     */
    public class Decorator {
    
        public static void main(String args[]) {
    
            BroadItch aa,bb,bb1,cc,cc1;
    
            aa = new Library();
            aa.getItch();
            System.out.println("---------------------");
            bb = new School(aa);
            bb1 = new HomeBuilder(bb);
            bb1.getItch();
            System.out.println("---------------------");
            cc = new Temple(bb1);
            cc1 = new HomeBuilder(cc);
            cc1.getItch();
    
    
        }
    
    }
    

      结果输出

    装饰者模式,针对单个对象,需要我们外部构造一个装饰者,然后把我们需要的示例加入装饰者的构造中,程序依次直接调用,外部看不出来,对象是怎么运行的。

  • 相关阅读:
    活动安排
    中国剩余定理
    欧拉回路
    单词游戏
    Ant Trip
    John's Trip
    太鼓达人
    相框
    原始生物
    Blockade
  • 原文地址:https://www.cnblogs.com/nicknailo/p/8834091.html
Copyright © 2020-2023  润新知