# Proxy Pattern

version 2.5.23

The Proxy Pattern allows one object to act as a pretend replacement for some other object. In general, whoever is using the proxy, doesn’t realise that they are not using the real thing. The pattern is useful when the real object is hard to create or use: it may exist over a network connection, or be a large object in memory, or be a file, database or some other resource that is expensive or impossible to duplicate.

## 1. Example

One common use of the proxy pattern is when talking to remote objects in a different JVM. Here is the client code for creating a proxy that talks via sockets to a server object as well as an example usage:

    class AccumulatorProxy {
        def accumulate(args) {
            def result
            def s = new Socket("localhost", 54321)
            s.withObjectStreams { ois, oos ->
                oos << args
                result = ois.readObject()
            }
            s.close()
            return result
        }
    }

    println new AccumulatorProxy().accumulate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    // => 55

Here is what your server code might look like (start this first):

    class Accumulator {
        def accumulate(args) {
            args.inject(0) { total, arg -> total += arg }
        }
    }

    def port = 54321
    def accumulator = new Accumulator()
    def server = new ServerSocket(port)
    println "Starting server on port $port"
    while(true) {
        server.accept() { socket ->
            socket.withObjectStreams { ois, oos ->
                def args = ois.readObject()
                oos << accumulator.accumulate(args)
            }
        }
    }