Unified Access Pattern Design


The pattern Unified Access describes a type safe access (reading and writing) to values of a map object (object that maps keys to values) for a such case where values have got different data types.

Structure (class model):

The model contains two classes: Class Diagram

Implementation in Java language

The implementation requires a generic type language support that's why the Java SE 5.0 or more must be used.
A MyMap class implements a simple map behavior and it contains two keys NAME and AGE.
import java.util.*;
public class MyMap {
    public static final Property<String> NAME = new Property<String>();
    public static final Property<Integer> AGE = new Property<Integer>();
    private Map<Property, Object> data = new HashMap<Property, Object>();
protected Object readValue(Property key) { return data.get(key); } protected void writeValue(Property key, Object value) { data.put(key, value); } }
All keys are an instance of a Property class, however each of them will provide a value of a different type.
If both classes (MyMap and Property) will be located in the same package, then it is possible to retain their visibility to protected so that no strange object can to use them.
public class Property<VALUE> {
public void setValue(MyMap map, VALUE value) { map.writeValue(this, value); } public VALUE getValue(MyMap map) { return (VALUE) map.readValue(this); } }
This pattern allows a value access by a methods of key only. It is possible to verify the method setValue accepts declared value type to write into map object and then method getValue returns the same data type only.
MyMap map = new MyMap();
MyMap.NAME.setValue(map, "Peter Prokop"); MyMap.AGE .setValue(map, 22); String name = MyMap.NAME.getValue(map); int age = MyMap.AGE.getValue(map); System.out.println(name + " is " + age);


The pattern design can be used like a special delegate of the POJO object. It's useful in case there is to need to refer a set of get method and to avoid a non-type value access by reflection API. Here are some samples of usage in a Java language Two projects has been built by this pattern design at first probably. There are jWorkSheet and Ujorm.
Both projects are available include a source code on SourceForge.net under an open license since 2007-10-24.
The pattern design was slightly extended; a final solution is described by two interfaces Another projects using the pattern:

About Author:

PPone(c) 2007-2011

Valid XHTML 1.0 Strict