1. 程式人生 > >GOF設計模式--代理模式和裝飾模式

GOF設計模式--代理模式和裝飾模式

一、裝飾模式

1、示例程式碼

// common interface
public interface IRunner {
    public void run();
}

//target class
public class Runner implements IRunner {
    @Override
    public void run() {
        System.out.println("運動員在跑步...");
    }
}

//decoration class
public class RunnerWithJet implements IRunner {
    private IRunner runner;
    
    public RunnerWithJet(IRunner runner) {
        this.runner = runner;
    }
    
    @Override
    public void run() {
        System.out.println("給運動員屁股後加一個推進裝置...");
        runner.run();
    }
}

2、概念

  • 裝飾模式指的是在不必改變原類檔案和使用繼承的情況下,動態地擴充套件一個物件的功能。它是通過建立一個包裝物件,也就是裝飾來包裹真實的物件 ;

 

二、代理模式

1、示例程式碼

public interface Person {
    void work();
}

public class Student implements Person {
    @Override
    public void work() {
        System.out.println("sudent is studying");
    }
}

public class ProxyStudent {
    private Student tar;

    public ProxyStudent(Student tar) {
        this.tar = tar;
    }

    public Object getProxyInstance(){
        return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(),
                new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("work".equals(method.getName())){
                    System.out.println("student is studying hard");
                    return null;
                }else{
                    return method.invoke(tar,args);
                }
            }
        });
    }

}

public class TestDemo {
    @Test
    public void test01(){
        Student stu = new Student();
        stu.work();
        Person proxyStu = (Person) new ProxyStudent(stu).getProxyInstance();
        proxyStu.work();
    }
}

2、概念

  • 用來修改已經具有的物件的方法,控制方法是否執行,或在方法執行之前和執行之後做一些額外的操作;

 

三、對比總結

1、代理模式和裝飾模式作用都是對特定類的功能進行增強;

2、裝飾模式:目標物件和裝飾物件要實現相同的介面;如果介面中的方法較多,程式碼會比較冗餘;

3、動態代理:不用和目標物件實現相同的介面,而且能夠控制方法是否執行,或在方法執行前後做一些額外的操作;目標物件至少 要實現一個介面,否則無法使用動態代理;

4、例項:spring 中的aop 本質就是使用的代理技術;而java.io包中的包裝流就是用的裝飾模式;