zoukankan      html  css  js  c++  java
  • 何为代理

    之前看技术书,每每看到“代理”这两字就懵。今天刚好有机会好好了解所谓的代理(Proxy)。

    为了更好了解代理关系,我们先来看看其他两种关系:组合继承

    1、组合

      只需将对象引用置于新类中即可。例如,假设你需要某个对象,它要具有多个String对象,几个基本类型数据,以及另一个类的对象。

    class WaterSource {
        private String s;
        WaterSource() {
            System.out.println("WaterSource");
            s = "Constructed";
         }
    
         public String toString() {
              return s;
         }
    }
    
    
    public class SprinklerSystem {
         private String value1, value2, value3, value4;
         private WaterSource source = new WaterSource();
         private int i;
         private floate f;
         public String toString() {....}
    .......
    }

    2、继承就不用多说了

    3、代理

      代理是继承与组合之间的中庸之道,因为我们可以将一个成员置于索要构造的类中(类似于组合),但与此同时,我们在新类中暴露了该成员对象的所有方法(就像继承)。例如:

       太空船需要一个控制模块:

    public class SpaceShipControls {
        void up(int velocity) {}
        void down(int velocity) {}
        void left(int velocity) {}
        void right(int velocity) {}
        void forward(int velocity) {}
        void back(int velocity) {}
        void turboBoost() {}
    }

      构造太空船的一种方式是使用继承:

    public class SpaceShip extends SpaceShipControls{
        private String name;
        
        public SpaceShip(String name) {
            this.name = name;
        }
        
        public String toString() {
            return name;
        }
        
        public static void main(String[] args) {
            SpaceShip protector = new SpaceShip("NSEA Protector");
            protector.forward(10);
        }
    }

      然而,SpaceShip并非真正的SpaceShipControls类型,即使你可以告诉SpaceShip向前运动。更准确地说,SpaceShip包含SpaceShipControls,与此同时,SpaceShipControls的所有方法在SpaceShip中暴露出来,代理正好解决这个问题:

    public class SpaceShipDelegation {
        private String name;
        private SpaceShipControls controls = new SpaceShipControls();
        public SpaceShipDelegation(String name) {
            this.name = name;
        }
        public void back(int velocity) {
            controls.back(velocity);
        }
        
        public void forward(int velocity) {
            controls.forward(velocity);
        }
        ......
    }
  • 相关阅读:
    Leetcode 349. Intersection of Two Arrays
    hdu 1016 Prime Ring Problem
    map 树木品种
    油田合并
    函数学习
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 102. Binary Tree Level Order Traversal
    Leetcode 101. Symmetric Tree
    poj 2524 Ubiquitous Religions(宗教信仰)
    pat 1009. 说反话 (20)
  • 原文地址:https://www.cnblogs.com/wiessharling/p/3593343.html
Copyright © 2011-2022 走看看