Implementation of persistent object and persistent decorator.

A Design Pattern for Type Extension With Facets and Decorators
by Chung-Yeung Pang
Listing 2. Implementation of persistent object and persistent decorator.


package Persistent_Type_Decorator;

import Type_Extension.*;
import java.sql.*;
import java.math.*;

public interface PersistentObject {
    public static final int new_state = 0;
    public static final int edited_state = new_state + 1;
    public static final int saved_state = edited_state + 1;

    public void fetchData() throws Exception;
    public void state(int _state);
    public int state();
    public void save() throws Exception;
    public void remove() throws Exception;
}

public class PersistentDecorator extends TypeDecorator {
    private Connection con;

    static {
        try {
          // register the driver with DriverManager
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected PersistentDecorator() {}

    public Connection getConnection() {
        return con;
    }

    public static PersistentDecorator _create(String url,
        String userID, String password, ExtensibleObject exObj)
        throws Exception {
        try {
            PersistentDecorator p = new PersistentDecorator();
            p.setName("PersistentDecorator");
            p.decorate(exObj);
            p.con = DriverManager.getConnection(url, userID,
              password);
            return p;
        }
        catch (Exception e) {
            throw e;
        }
    }
}