Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用動態代理打造「空物件」的實戰範例

在物件導向設計裡,「空物件模式」(Null Object Pattern)常被用來免除層出不窮的 null 判斷。本文以一台除雪機器人為例,示範如何借助 Java 的動態代理(Dynamic Proxy),在執行期動態生成一個安全、可控的「空」物件,讓呼叫端不必再為 null 而煩惱。

核心思路

關鍵在於 Proxy.newProxyInstance:我們把目標介面 Robot 與一個標記介面 Null 一起交給代理,並透過 InvocationHandler 攔截所有方法呼叫,將它們導向一個內部定義的 NullRobot。如此一來,任何對空物件的方法呼叫都會得到合理的預設回應,而非拋出例外。

package com.eric.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SnowRemovalRobot implements Robot {
    // 生成一個「空」的機器人物件
    static Robot generateNullRobotObj(Robot obj) {
        return (Robot) Proxy.newProxyInstance(
            Robot.class.getClassLoader(),
            new Class[] { Robot.class, Null.class },
            new NullRobotHandler(obj.getClass()));
    }

    public static void main(String[] args) {
        Robot.Test.test(new SnowRemovalRobot("sample "));
        System.out.println();
        Robot.Test.test(generateNullRobotObj(new SnowRemovalRobot("sample ")));
    }

    private String name;

    public SnowRemovalRobot(String name) {
        this.name = name;
    }

    public String name() {
        return name;
    }

    public String model() {
        return "SnowBot Series 11";
    }

    public List<Operation> operations() {
        return Arrays.asList(
            new Operation() {
                public String description() {
                    return name + " can shovel snow";
                }
                public void command() {
                    System.out.println(name + " shoveling snow");
                }
            },
            new Operation() {
                public String description() {
                    return name + " can chip ice";
                }
                public void command() {
                    System.out.println(name + " chipping ice");
                }
            },
            new Operation() {
                public String description() {
                    return name + " can clear the roof";
                }
                public void command() {
                    System.out.println(name + " clearing roof");
                }
            });
    }
}

// 空物件處理器:以動態代理生成特殊的 null 物件
class NullRobotHandler implements InvocationHandler {
    private String name;
    private Robot nullRobot = new NullRobot();

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(nullRobot, args);
    }

    public NullRobotHandler(Class<? extends Robot> type) {
        name = "NULL " + type.getSimpleName() + " obj";
    }

    class NullRobot implements Robot, Null {
        public String name() {
            return name;
        }
        public String model() {
            return name;
        }
        public List<Operation> operations() {
            return Collections.emptyList();
        }
    }
}

interface Robot {
    String name();
    String model();
    List<Operation> operations();

    class Test {
        static void test(Robot robot) {
            System.out.println("name " + robot.name());
            System.out.println("model " + robot.model());
            for (Operation ope : robot.operations()) {
                System.out.print("description:" + ope.description() + " command:");
                ope.command();
            }
        }
    }
}

interface Operation {
    String description();
    void command();
}

小結

透過動態代理,我們能在不新增大量空實作類別的前提下,為任意介面補上「空物件」。這在需要預設行為、又不想四處寫 if (obj != null) 的場景中格外好用。

Copyright © Linux教程網 All Rights Reserved