zoukankan      html  css  js  c++  java
  • delegate模式

    今天看实验室一个项目的源码,其中设计模式随处可见。。

    这是一个Mesh类,其中有一个friend class : MeshDelegate, 显然是一个delegate模式了。

    参考Wiki上的条目:

    一个简单的用法:

     class RealPrinter { // the "delegate"
         void print() { 
           System.out.print("something"); 
         }
     }
     
     class Printer { // the "delegator"
         RealPrinter p = new RealPrinter(); // create the delegate 
         void print() { 
           p.print(); // delegation
         } 
     }
     
     public class Main {
         // to the outside world it looks like Printer actually prints.
         public static void main(String[] args) {
             Printer printer = new Printer();
             printer.print();
         }
     }

    instead of performing one of its stated tasks, delegates that task to an associated helper object. It passes the buck, so to speak (technically, an Inversion of Responsibility). The helper object is called the delegate. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.

    一个更复杂,也可以体现用途的例子如下:

    interface I {
         void f();
         void g();
     }
     
     class A implements I {
         public void f() { System.out.println("A: doing f()"); }
         public void g() { System.out.println("A: doing g()"); }
     }
     
     class B implements I {
         public void f() { System.out.println("B: doing f()"); }
         public void g() { System.out.println("B: doing g()"); }
     }
     
     class C implements I {
         // delegation
         I i = new A();
     
         public void f() { i.f(); }
         public void g() { i.g(); }
     
         // normal attributes
         public void toA() { i = new A(); }
         public void toB() { i = new B(); }
     }
     
     
     public class Main {
         public static void main(String[] args) {
             C c = new C();
             c.f();     // output: A: doing f()
             c.g();     // output: A: doing g()
             c.toB();
             c.f();     // output: B: doing f()
             c.g();     // output: B: doing g()
         }
     }
     
    上述例子中,可以自由切换f及g的实现。
     
  • 相关阅读:
    统计一段文字中出现频率最高的10个单词(c语言)
    java之过滤器Filter (应用场景)
    java之过滤器Filter
    Spring AOP
    清华大学iCenter区块链公开课 第二节
    学习区块链 第一节 精通比特币
    使用Shiro登录成功后,跳转到之前访问的页面实现
    windows下系统移植到linux下出现的问题
    mysql分页查询
    安卓开发随笔
  • 原文地址:https://www.cnblogs.com/justin_s/p/1898952.html
Copyright © 2011-2022 走看看