Package com.thoughtworks.proxy.toys.dispatch

A toy to dispatch method calls to different objects.

See:
          Description

Class Summary
Dispatching<T> Proxy factory for dispatching proxy instances.
Dispatching.DispatchingBuild<T>  
Dispatching.DispatchingWith<T>  
DispatchingInvoker Invoker that dispatches all invocations to different objects according the membership of the method.
 

Exception Summary
DispatchingException An exception if a type cannot be dispatched.
 

Package com.thoughtworks.proxy.toys.dispatch Description

A toy to dispatch method calls to different objects.

The package provides a proxy factory creating proxies, that are used to delegate method calls to objects implementing the different types of the proxy. Main component is the Dispatching toy, a utility class creating these proxies. Such a proxy contains an instance of a DispatchingInvoker that routes all calls. The DispatchingInvoker will only call methods on an object if it implements the method's type. The dispatcher will not look out for signature compatible methods on the objects to dispatch.

The following example uses the proxy as a container for different objects, that have distinct interfaces, but are accessed as single object:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ArrayList<String> list = new ArrayList<String>();
TreeMap<Object, Object> map = new TreeMap<Object, Object>();

Checksum checksum = Dispatching.proxy(Checksum.class, DataInput.class, DataOutput.class, List.class)
    .with(list, new CRC32(), new DataInputStream(new ByteArrayInputStream("Hello Proxy!".getBytes())),
        new DataOutputStream(outputStream), map)
    .build();

DataOutput.class.cast(checksum).writeBytes("Chameleon");
@SuppressWarnings("unchecked")
List stringLlist = List.class.cast(checksum);
stringLlist.add("Frankenstein");

System.out.println("Read a line: " + DataInput.class.cast(checksum).readLine());
System.out.println("Once written: " + outputStream.toString());
System.out.println("List contains: " + list.toString());
System.out.println("Current CRC32 value: " + checksum.getValue());

The number of objects must not necessarily match the number of interfaces, that are implemented by the created proxy, but every interface must be implemented by at least one object:

RandomAccessFile file = new RandomAccessFile(tempFile, "rw");
Object proxy = Dispatching.proxy(DataInput.class, DataOutput.class)
    .with(file)
    .build();

DataOutput.class.cast(proxy).writeBytes("One matches both");
file.seek(0);
System.out.println("Just written: " + DataInput.class.cast(proxy).readLine());



Copyright © 2005-2010 Codehaus. All Rights Reserved.