Proxy năng động sẽ trì hoãn instantiation cho đến khi bạn quyết định nó là cần thiết. Tất cả các phương pháp sẽ không làm gì cả cho đến khi khởi tạo này được hoàn tất. Lớp này có thể được sử dụng để bọc các lớp học khá là đắt tiền để tạo ra hoặc mất một thời gian dài để khởi tạo. | CHAPTER 14 THE PROXY PATTERN 213 This dynamic proxy will defer instantiation until you decide it is needed. All methods will do nothing until this initialization is complete. This class can be used to wrap classes that are computationally expensive to create or that take a long time to instantiate. Benefits of the Proxy Pattern Each type of proxy has a different set of benefits. The remote proxy allows you to treat a remote resource as a local JavaScript object. This is obviously a huge benefit it reduces the amount of glue code you have to write to access the remote resource and provides a single interface for interacting with it. You only have to change your code in one place if the API provided by the remote resource changes. It also stores all of the data associated with the resource in a single place. This includes the URL of the resource the data format used and the structure of the commands and responses. If there is more than one web service it is possible to create a general remote proxy as an abstract class and then subclass it for each of the web services that you need to access. The virtual proxy has a very different set of benefits. Unlike most of the patterns described in this book it will not reduce code duplication or make your objects more modular. In fact it will add more code to your pages code that isn t strictly needed. What it does provide is efficiency. This is an optimization pattern and should be used only when a resource is expensive to create or maintain and needs a proxy to control when and how it is created. In this situation it excels. It allows you to access all of the features of the real subject without worrying about whether it has been instantiated. It also takes care of displaying any loading messages or dummy user interfaces UIs until the real subject has finished loading. In a page where speed is crucial a virtual proxy can be used to delay the instantiation of large objects until after the other elements in the page have .