Adapter Pattern

Hello All,
I am trying to implement the GOF Adapter Pattern and I have the following classes. The purpose is to read the database name from a properties file and instantiate the correct database class. For example if the properties file reads
database.vendor=OracleDatabase
then the code should instantiate the OracleDatabase class file and invoke methods on that. Here is some of the code that I have written but I don't seem to put it all together. Any help will be greatly appreciated.
1) Interface (IDatabaseAdapter):
<code>
public interface IDatabaseAdapter
public String getDatabase(String fileName);
</code>
2) ConnectionFactory (implements IDatabaseAdapter)
<code>
import java.io.*;
import java.sql.*;
import java.util.*;
public class ConnectionFactory implements IDatabaseAdapter
private IDatabaseAdapter ida;
private static ConnectionFactory instance = null;
private static String fileName = "dbvendor.properties";
private String vendorName = "";
public String getDatabase(String fileName)
try
Properties props = new Properties();
props.load(new FileInputStream(fileName));
vendorName = props.getProperty("database.vendor");
System.out.println("DB Vendor: "+vendorName);
return vendorName;
catch(MissingResourceException e) {
System.err.println("Missing Resource: " + e.getMessage());
return null;
catch (FileNotFoundException fnfe)
fnfe.printStackTrace();
return null;
catch (IOException ioe)
ioe.printStackTrace();
return null;
public static synchronized ConnectionFactory getInstance()
if (instance == null)
instance = new ConnectionFactory();
return instance;
public IDatabaseAdapter getDatabaseAdapter(String fileName)
try
if (ida == null)
ida = (IDatabaseAdapter)Class.forName(getDatabase(fileName)).newInstance();
System.out.println("Calling "+getDatabase(fileName)+" instance");
return ida;
catch (Exception e)
e.printStackTrace();
return ida;
</code>
3) I need to use this in the code now, something like this:
cached = new CachedConnection(<get the name from the Adapters>.getConnection(bindName))
Any other suggestions will be helpful.
Thanks

Any other suggestions will be helpful.Here are a couple of suggestions:
1) Ask a direct, precise question, rather than just posting bare minimum skeleton code and asking others to fill it in for you.
2) [code] and[/code], not <code> and <code>

Similar Messages

  • Adapter pattern and interfaces

    Hi all! This year I started to study java language and as a person who used c language for a long time, I have some questions.If you can help me I ll appreciate that.
    1-Can anybody tell me why we use Adapter pattern?I already read a lot about it but the point that I dont understand is,its always said that we use this pattern in case of an existing class does not support an interface that we want to implement.This is the main point where I have troubles.I mean why and when a class does not support an interface?According to my readings about interfaces,I think that interfaces are just for defining the names of the methods.When we create a class we implement any interface that we want and we fill inside of these methods in the class.So how a class can not support an interface when thats ourself who fill the inside of these methods?
    I understood the main idea of this pattern but as you can see in deep inside I cant imagine where I can benefit from this pattern because I think that instead of using an interface we can just define the methods in the class and we dont have to use neither the adapter nor an interface.
    2-Why interfaces are so important if we dont work in a big project.I mean according to my readings I think that interfaces are just guides for developper who are splitting the project.Why I have to use an interface?We can just define the names of the methods if I am not wrong so why they are so important?
    Thank you very much in advance and good day to all.

    vitamini.kabuunda wrote:
    Hi all! This year I started to study java language and as a person who used c language for a long time, I have some questions.If you can help me I ll appreciate that.
    1-Can anybody tell me why we use Adapter pattern?I already read a lot about it but the point that I dont understand is,its always said that we use this pattern in case of an existing class does not support an interface that we want to implement.This is the main point where I have troubles.I mean why and when a class does not support an interface?According to my readings about interfaces,I think that interfaces are just for defining the names of the methods.When we create a class we implement any interface that we want and we fill inside of these methods in the class.So how a class can not support an interface when thats ourself who fill the inside of these methods?
    I understood the main idea of this pattern but as you can see in deep inside I cant imagine where I can benefit from this pattern because I think that instead of using an interface we can just define the methods in the class and we dont have to use neither the adapter nor an interface.when either the class or interface (or both) are outside of your control, you would use an adapter
    2-Why interfaces are so important if we dont work in a big project.I mean according to my readings I think that interfaces are just guides for developper who are splitting the project.Why I have to use an interface?We can just define the names of the methods if I am not wrong so why they are so important?you don't have to use an interface, but if you ever want to create different implementations and not have to modify the code using it, an interface will come in handy

  • What is diff bet. facade and adapter pattern?

    What is diff bet. facade and adapter pattern?

    An adapter is an interpretor between two classes, it converts the interface of one class so it can be used by another expecting that interface. Adapters are also known to be a concrete class that implements the all interface methods so that objects don't have to produce all interface methods.
    The delegate pattern is the one stop shop that handles requests, and performs those requests on a high number of subsystems. For example, the session bean facade has verb methods that once involked will gather multiple entity beans to perform that one duty.
    Dan

  • Java Program with Adapter / Facade Pattern

    Hey All:
    I'm very new to the Java language and have been given a fairly complicated (to me) program to do for a course I'm taking. The following is the scenario. I'll post code examples I have and any help will be greatly appreciated. Let me apologize ahead of time for all the code involved and say thank you in advance :).
    The program is the follow the following logic:
    Organizations A's Client (Org_A_Client.java) uses Organization A's interface (Org_A_Interface.java) but we want A's Client to also be able to use Organization B's services as well (Org_B_FileAuthorMgr.java, Org_B_FileDateMgr.java, Org_B_FileIOMgr.java).
    Now a portion of this program also involves validating an xml file to it's dtd, extracting information from that source xml file through the use of a XMLTransformation file, and applying the transformation to produce a targetxml file which is then validated against a target DTD. (I've done this portion as I have a much better understanding of XML).
    At this point we have been given the following java classes:
    Org_A_Client.java
    package project4;
    /* This class is the Organization A Client.
    It reads a source xml file as input and it invokes methods defined in the
    Org_A_Doc_Interface Interface on a class that implements that interface */
    import java.io.*;
    import java.util.Scanner;
    public class Org_A_Client {
         // Define a document object of type Org_A_Doc_Interface
         private Org_A_Doc_Interface document;
         // The Org_A_Client constructor
         public Org_A_Client() {
              // Instanciate the document object with a class that implements the
              // Org_A_Doc_Interface
              this.document = new Adapter();
         // The Main Method
         public static void main(String Args[]) {
              // Instanciate a Client Object
              Org_A_Client client = new Org_A_Client();
              // Create a string to store user input
              String inputFile = null;
              System.out.print("Input file name: ");
              // Read the Source xml file name provided as a command line argument
              Scanner scanner = new Scanner(System.in);
              inputFile = scanner.next();
              // Create a string to store user input
              String fileID = null;
              System.out.print("Input file ID: ");
              // Read the Source xml file name provided as a command line argument
              fileID = scanner.next();
              //Convert the String fileID to an integer value
              int intFileID = Integer.parseInt(fileID);
              if (inputFile != null && !inputFile.equals("")) {
                   // Create and empty string to store the source xml file
                   String file = "";
                   try {
                        // Open the file
                        FileInputStream fstream = new FileInputStream(inputFile);
                        // Convert our input stream to a
                        // BufferedReader
                        BufferedReader d = new BufferedReader(new InputStreamReader(
                                  fstream));
                        // Continue to read lines while
                        // there are still some left to read
                        String temp = "";
                        while ((temp = d.readLine()) != null) {
                             // Add file contents to a String
                             file = file + temp;
                        d.close();
                        // The Client Calls the archiveDoc Method on the Org_A_Document
                        // object
                        if (!file.equals("")) {
                             client.document.archiveDoc(file, intFileID);
                   } catch (Exception e) {
                        System.err.println("File input error");
              } else
                   System.out.println("Error: Invalid Input");
    Org_A_Doc_Interface.java
    package project4;
    /* This class is the Standard Organization A Document Interface.
    * It defines various methods that any XML document object
    * in Organization A should understand
    public interface Org_A_Doc_Interface {
         void archiveDoc(String XMLSourceDoc, int fileID);
         String getDoc(int fileID);
         String getDocDate(int fileID);
         void setDocDate(String date, int fileID);
         String[] getDocAuthors(int fileID);
         void setDocAuthor(String authorname, int position, int fileID);
    Org_B_FileAuthorMgr.java
    package project4;
    public class Org_B_FileAuthorMgr {
         // This function returns the list of file authors for the file that matches
         // the given fileID. For the purpose of the assignment we have not
         // provided any implementation
         public String[] getFileAuthors(String fileID) {
              // Since we do not have any implementation, we just return a
              // null String array of size 2
              return new String[2];
         // This function sets the authorname at a given position for the file that
         // matches the given fileID.
         // For the purpose of the assignment we have not provided any
         // implementation
         public void setFileAuthor(String authorname, int position, String fileID) {
    Org_B_FileDateMgr.java
    package project4;
    public class Org_B_FileDateMgr {
         // This function returns the creation date for the file that matches
         // the given fileID. For the puprposes of the assignment we have not
         // provided any implementation but only return a date string.
         String getFileDate(String fileID) {
              return "1st Nov 2007";
         // This function sets the creation datefor the file that
         // matches the given fileID.
         // For the puprposes of the assignment we have not provided any
         // implementation
         void setFileDate(String date, String fileID) {
    Org_B_FileIOMgr.java
    package project4;
    import java.io.*;
    public class Org_B_FileIOMgr {
         // This class variable stores the file location for all files
         private String fileLocation;
         // This function stores the given String of XMLTargetFile at the
         // fileLocation which is set using the setFileLocation method
         boolean storeFile(String XMLTargetFile, String fileID) {
              if (this.fileLocation != null) {
                   FileOutputStream out; // declare a file output object
                   PrintStream p; // declare a print stream object
                   try {
                        // Create a new file output stream
                        // connected to "myfile.txt"
                        out = new FileOutputStream(fileLocation);
                        // Connect print stream to the output stream
                        p = new PrintStream(out);
                        p.println(XMLTargetFile);
                        p.close();
                        System.out.println("MSG from Org_B_FileIOMgr: Target File Successfully Saved with ID " + fileID);
                   } catch (Exception e) {
                        System.err.println("Error writing to file");
                        return false;
                   return true;
              System.out.println("MSG from Org_B_FileIOMgr: Please set the File Location before storing a file");
              return false;
         // This function sets the fileLocation where the file will be stored for
         // archive
         void setFileLocation(String fileLocation) {
              this.fileLocation = fileLocation;
         // This function retreives the file that matches the given fileID and
         // returns its contents as a string
         // Only for the puprposes of the assignment we have not provided any
         // implementation
         String retrieveFile(String fileID) {
              return "This is the retreived file";
    }Also, we've been given the following two classes which I believe are used to help with the xml transformation using SAX (I've done alot of research regarding parsing XML using SAX/DOM so I understand how it works, but I'm really struggling with the integration...)
    FileDetailsProvider.java
    package project4;
    /* This is the FileDetailsProvider Class which implements the Singleton design pattern.
    The class can be used in the following manner:
         // Declare a object of the class type
            FileDetailsProvider fp;
            // Get the single instance of this class by calling the getInstance static method
            fp= FileDetailsProvider.getInstance();
            // Initialize the class with providing it the file name of our configuration XML file
              fp.loadConfigFile("C:\\assignment4\\XMLTransformerConfig.xml");
    import java.io.File;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    public class FileDetailsProvider {
         private InputHandler handler;
         private SAXParserFactory factory;
         private SAXParser saxParser;
         private final static FileDetailsProvider INSTANCE = new FileDetailsProvider();
         // Private constructor suppresses generation of a (public) default
         // constructor
         private FileDetailsProvider() {
              // Create the content handler
              handler = new InputHandler();
              // Use the default (non-validating) parser
              factory = SAXParserFactory.newInstance();
              // Validate the XML as it is parsed by the SAX Parser: only works
              // for dtd's
              factory.setValidating(true);
              try {
                   saxParser = factory.newSAXParser();
              } catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(0);
         // This is the public static method that returns a single instance of the
         // class everytime it is invoked
         public static FileDetailsProvider getInstance() {
              return INSTANCE;
         // After instantiation this method needs to be called to load the XMLTransformer Configuration xml
         // file that includes the xsl file details needed
         // for our assignment
         public void loadConfigFile(String configFile) {
              try {
                   INSTANCE.saxParser.parse(new File(configFile), INSTANCE.handler);
              } catch (Throwable t) {
                   t.printStackTrace();
                   // Exceptions thrown if validation fails or file not found
                   System.out.println();
                   System.out.println("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\Transform.xsl");
                   System.exit(0);
         // This method return the xsl file name
         public String getXslfileName() {
              return handler.getXslfileName();
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return handler.getXslfileLocation();
    InputHandler.java
    package project4;
    /* This class is used by the FileDetailsProvider Class to read the XMLTranformerConfig xml
    * file using a SAX parser which is a event based parser
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    public class InputHandler extends DefaultHandler {
         private String xslfileName = "";
         private String xslfileLocation = "";
         int fileName = 0, fileLoc = 0, DTDUrl = 0;
         boolean endOfFile = false;
         public InputHandler() {
         // Start XML Document Event
         public void startDocument() throws SAXException {
              super.startDocument();
         // End XML Document Event
         public void endDocument() throws SAXException {
              super.endDocument();
              // display();
         public void display() {
              System.out.println(xslfileName);
              System.out.println(xslfileLocation);
         public void startElement(String uri, String localName, String qName,
                   Attributes attributes) throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
              if (eName.equals("File Name:")) {
                   fileName++;
              } else if (eName.equals("File Location:")) {
                   fileLoc++;
         public void endElement(String uri, String localName, String qName)
                   throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
         public void characters(char ch[], int start, int length)
                   throws SAXException {
              String str = new String(ch, start, length);
              // Getting the Transform File Location
              if (fileLoc == 1 && xslfileLocation.equals("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\")) {
                   xslfileLocation = str;
              // Getting the Transform File Name
              if (fileName == 1 && xslfileName.equals("Transform.xsl")) {
                   xslfileName = str;
         public void processingInstruction(String target, String data)
                   throws SAXException {
         // treat validation errors as fatal
         public void error(SAXParseException e) throws SAXParseException {
              throw e;
         // This method return the xsl file name
         public String getXslfileName() {
              return xslfileName;
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return xslfileLocation;
    }I need to do the following:
    1. Create an adapter class and a facade class that allows Client A through the use of Organization's A interface to to use Organization B's services.
    2. Validate the Source XML against its DTD
    3. Extract information regarding the XSL file from the given XMLTransformerConfig xml file
    4. Apply the XSL Transformation to the source XML file to produce the target XML
    5. Validate the Target XML against its DTD
    Now I'm not asking for a free handout with this program completed as I really want to learn how to do a program like this, but I really don't have ANY prior java experience other than creating basic classes and methods. I don't know how to bring the whole program together in order to make it all work, so any guidance for making this work would be greatly appreciated.
    I've researched over 100 links on the web and found alot of useful information on adapter patterns with java and facade patterns, as well as SAX/DOM examples for parsing xml documents and validation of the DTD, but I can't find anything that ties this all together. Your help will be saving my grade...I hope :). Thanks so much for reading this.

    No one has anything to add for working on this project? I could really use some help, especially for creating the code for the adapter/facade pattern classes.

  • New(?) pattern looking for a good home

    Hi everyone, this is my second post to sun forums about this, I initially asked people for help with the decorator and strategy pattern on the general Java Programming forum not being aware that there was a specific section for design pattern related questions. Since then I refined my solution somewhat and was wondering if anyone here would take a look. Sorry about the length of my post, I know it's best to keep it brief but in this case it just seemed that a fully functional example was more important than keeping it short.
    So what I'd like to ask is whether any of you have seen this pattern before and if so, then what is it called. I'm also looking for some fresh eyes on this, this example I wrote seems to work but there are a lot of subtleties to the problem so any help figuring out if I went wrong anywhere is greatly appreciated. Please do tell me if you think this is an insane approach to the problem -- in short, might this pattern have a chance at finding a good home or should it be put down?
    The intent of the pattern I am giving below is to modify behavior of an object at runtime through composition. In effect, it is like strategy pattern, except that the effect is achieved by wrapping, and wrapping can be done multiple times so the effect is cumulative. Wrapper class is a subclass of the class whose instance is being wrapped, and the change of behavior is accomplished by overriding methods in the wrapper class. After wrapping, the object "mutates" and starts to behave as if it was an instance of the wrapper class.
    Here's the example:
    public class Test {
         public static void main(String[] args) {
              double[] data = { 1, 1, 1, 1 };
              ModifiableChannel ch1 = new ModifiableChannel();
              ch1.fill(data);
              // ch2 shifts ch1 down by 1
              ModifiableChannel ch2 = new DownShiftedChannel(ch1, 1);
              // ch3A shifts ch2 down by 1
              ModifiableChannel ch3A = new DownShiftedChannel(ch2, 1);
              // ch3B shifts ch2 up by 1, tests independence from ch3A
              ModifiableChannel ch3B = new UpShiftedChannel(ch2, 1);
              // ch4 shifts ch3A up by 1, data now looks same as ch2
              ModifiableChannel ch4 = new UpShiftedChannel(ch3A, 1);
              // print channels:
              System.out.println("ch1:");
              printChannel(ch1);
              System.out.println("ch2:");
              printChannel(ch2);
              System.out.println("ch3A:");
              printChannel(ch3A);
              System.out.println("ch3B:");
              printChannel(ch3B);
              System.out.println("ch4:");
              printChannel(ch4);
         public static void printChannel(Channel channel) {
              for(int i = 0; i < channel.size(); i++) {
                   System.out.println(channel.get(i) + "");
              // Note how channel's getAverage() method "sees"
              // the changes that each wrapper imposes on top
              // of the original object.
              System.out.println("avg=" + channel.getAverage());
    * A Channel is a simple container for data that can
    * find its average. Think audio channel or any other
    * kind of sampled data.
    public interface Channel {
         public void fill(double[] data);
         public double get(int i);
         public double getAverage();
         public int size();
    public class DefaultChannel implements Channel {
         private double[] data;
         public void fill(double[] data) {
              this.data = new double[data.length];
              for(int i = 0; i < data.length; i++)
                   this.data[i] = data;
         public double get(int i) {
              if(i < 0 || i >= data.length)
                   throw new IndexOutOfBoundsException("Incorrect index.");
              return data[i];
         public double getAverage() {
              if(data.length == 0) return 0;
              double average = this.get(0);
              for(int i = 1; i < data.length; i++) {
                   average = average * i / (i + 1) + this.get(i) / (i + 1);
              return average;
         public int size() {
              return data.length;
    public class ModifiableChannel extends DefaultChannel {
         protected ChannelModifier modifier;
         public void fill(double[] data) {
              if (modifier != null) {
                   modifier.fill(data);
              } else {
                   super.fill(data);
         public void _fill(double[] data) {
              super.fill(data);
         public double get(int i) {
              if(modifier != null)
                   return modifier.get(i);
              else
                   return super.get(i);
         public double _get(int i) {
              return super.get(i);
         public double getAverage() {
              if (modifier != null) {
                   return modifier.getAverage();
              } else {
                   return super.getAverage();
         public double _getAverage() {
              return super.getAverage();
    public class ChannelModifier extends ModifiableChannel {
         protected ModifiableChannel delegate;
         protected ModifiableChannel root;
         protected ChannelModifier tmpModifier;
         protected boolean doSwap = true;
         private void pre() {
              if(doSwap) { // we only want to swap out modifiers once when the
                   // top call in the chain is made, after that we want to
                   // proceed without it and finally restore doSwap to original
                   // state once ChannelModifier is reached.
                   tmpModifier = root.modifier;
                   root.modifier = this;
                   if(delegate instanceof ChannelModifier)
                        ((ChannelModifier)delegate).doSwap = false;
         private void post() {
              if (doSwap) {
                   root.modifier = tmpModifier;
              } else {
                   if(delegate instanceof ChannelModifier)
                             ((ChannelModifier)delegate).doSwap = true;
         public ChannelModifier(ModifiableChannel delegate) {
              if(delegate instanceof ChannelModifier)
                   this.root = ((ChannelModifier)delegate).root;
              else
                   this.root = delegate;
              this.delegate = delegate;
         public void fill(double[] data) {
              pre();
              if(delegate instanceof ChannelModifier)
                   delegate.fill(data);
              else
                   delegate._fill(data);
              post();
         public double get(int i) {
              pre();
              double result;
              if(delegate instanceof ChannelModifier)
                   result = delegate.get(i);
              else
                   result = delegate._get(i);
              post();
              return result;
         public double getAverage() {
              pre();
              double result;
              if(delegate instanceof ChannelModifier)
                   result = delegate.getAverage();
              else
                   result = delegate._getAverage();
              post();
              return result;
         public int size() {
              //for simplicity no support for modifying size()
              return delegate.size();
    public class DownShiftedChannel extends ChannelModifier {
         private double shift;
         public DownShiftedChannel(ModifiableChannel channel, final double shift) {
              super(channel);
              this.shift = shift;
         @Override
         public double get(int i) {
              return super.get(i) - shift;
    public class UpShiftedChannel extends ChannelModifier {
         private double shift;
         public UpShiftedChannel(ModifiableChannel channel, final double shift) {
              super(channel);
              this.shift = shift;
         @Override
         public double get(int i) {
              return super.get(i) + shift;
    Output:ch1:
    1.0
    1.0
    1.0
    1.0
    avg=1.0
    ch2:
    0.0
    0.0
    0.0
    0.0
    avg=0.0
    ch3A:
    -1.0
    -1.0
    -1.0
    -1.0
    avg=-1.0
    ch3B:
    1.0
    1.0
    1.0
    1.0
    avg=1.0
    ch4:
    0.0
    0.0
    0.0
    0.0
    avg=0.0

    jduprez wrote:
    Hello,
    unless you sell your design better, I deem it is an inferior derivation of the Adapter pattern.
    In the Adapter pattern, the adaptee doesn't have to be designed to support adaptation, and the instance doesn't even know at runtime whether it is adapted.
    Your design makes the "modifiable" class aware of the modification, and it needs to be explicitly designed to be modifiable (in particular this constrains the implementation hierarchy). Overall DesignPattern are meant to provide flexibility, your version offers less flexibility than Adapter, as it poses more constraint on the modifiable class.
    Another sign of this inflexibility is your instanceof checks.
    On an unrelated note, I intensely dislike your naming choice of fill() vs _fill()+, I prefer more explicit names (I cannot provide you one as I didn't understand the purpose of this dual method, which a good name would have avoided, by the way).
    That being said, I haven't followed your original problem, so I am not aware of the constraints that led you to this design.
    Best regards,
    J.
    Edited by: jduprez on Mar 22, 2010 10:56 PMThank you for your input, I will try to explain my design better. First of all, as I understand it the Adapter pattern is meant to translate one interface into another. This is not at all what I am trying to do here, I am trying to keep the same interface but modify behavior of objects through composition. I started thinking about how to do this when I was trying to apply the Decorator pattern to filter some data. The way I would do that in my example here is to write an AbstractChannelDecorator that delegates all methods to the Channel it wraps:
    public abstract class AbstractChannelDecorator implements Channel {
            protected Channel delegate;
    ...// code ommitted
         public double getAverage() {
              return delegate.getAverage();
    ...// code ommitted
    }and then to filter the data I would extend it with concrete classes and override the appropriate methods like so:
    public class DownShiftedChannel extends AbstractChannelDecorator {
         ...// code ommitted
         public double get(int i) {
              return super.get(i) - shift;
           ...// code ommitted
    }(I am just shifting the data here to simplify the examples but a more realistic example would be something like a moving average filter to smooth the data).
    Unfortunately this doesn't get me what I want, because getAverage() method doesn't use the filtered data unless I override it in the concrete decorator, but that means I will have to re-implement the whole algorithm. So that's pretty much my motivation for this, how do I use what on the surface looks like a Decorator pattern, but in reality works more like inheritance?
    Now as to the other points of critique you mentioned:
    I understand your dislike for such method names, I'm sorry about that, I had to come up with some way for the ChannelModifier to call ModifiableChannel's super's method equivalents. I needed some way to have the innermost wrapped object to initiate a call to the topmost ChannelModifier, but only do it once -- that was one way to do it. I suppose I could have done it with a flag and another if/else statement in each of the methods, or if you prefer, the naming convention could have been fill() and super_fill(), get() and super_get(), I didn't really think that it was that important. Anyway, those methods are not meant to be used by any other class except ChannelModifier so I probably should have made them protected.
    The instanceof checks are necessary because at some point ChannelModifier instance runs into a delegate that isn't a ChannelModifier and I have to somehow detect that, because otherwise instead of calling get() I'd call get() which in ModifiableChannel would take me back up to the topmost wrapper and start the whole call chain again, so we'd be in infinite recursion. But calling get() allows me to prevent that and go straight to the original method of the innermost wrapped object.
    I completely agree with you that the example I presented has limited flexibility in supporting multiple implementations. If I had two different Channel implementations I would need two ModifiableChannel classes, two ChannelModifiers, and two sets of concrete implementations -- obviously that's not good. Not to worry though, I found a way around that. Here's what I came up with, it's a modification of my original example with DefaultChannel replaced by ChannelImplementation1,2:
    public class ChannelImplementation1 implements Channel { ... }
    public class ChannelImplementation2 implements Channel { ... }
    // this interface allows implementations to be interchangeable in ChannelModifier
    public interface ModifiableChannel {
         public double super_get(int i);
         public double super_getAverage();
         public void setModifier(ChannelModifier modifier);
         public ChannelModifier getModifier();
    public class ModifiableChannelImplementation1
              extends ChannelImplementation1
              implements ModifiableChannel {
         ... // see DefaultChannel in my original example
    public class ModifiableChannelImplementation2
              extends ChannelImplementation1
              implements ModifiableChannel { ...}
    // ChannelModifier is a Channel, but more importantly, it takes a Channel,
    // not any specific implementation of it, so in effect the user has complete
    // flexibility as to what implementation to use.
    public class ChannelModifier implements Channel {
         protected Channel delegate;
         protected Channel root;
         protected ChannelModifier tmpModifier;
         protected boolean doSwap = true;
         public ChannelModifier(Channel delegate) {
              if(delegate instanceof ChannelModifier)
                   this.root = ((ChannelModifier)delegate).root;
              else
                   this.root = delegate;
              this.delegate = delegate;
         private void pre() {
              if(doSwap) {
                   if(root instanceof ModifiableChannel) {
                        ModifiableChannel root = (ModifiableChannel)this.root;
                        tmpModifier = root.getModifier();
                        root.setModifier(this);
                   if(delegate instanceof ChannelModifier)
                        ((ChannelModifier)delegate).doSwap = false;
         private void post() {
              if (doSwap) {
                   if(root instanceof ModifiableChannel) {
                        ModifiableChannel root = (ModifiableChannel)this.root;
                        root.setModifier(tmpModifier);
              } else {
                   if(delegate instanceof ChannelModifier)
                             ((ChannelModifier)delegate).doSwap = true;
         public void fill(double[] data) {
              delegate.fill(data);
         public double get(int i) {
              pre();
              double result;
              if(delegate instanceof ModifiableChannel)
    // I've changed the naming convention from _get() to super_get(), I think that may help show the intent of the call
                   result = ((ModifiableChannel)delegate).super_get(i);
              else
                   result = delegate.get(i);               
              post();
              return result;
         public double getAverage() {
              pre();
              double result;
              if(delegate instanceof ModifiableChannel)
                   result = ((ModifiableChannel)delegate).super_getAverage();
              else
                   result = delegate.getAverage();
              post();
              return result;
         public int size() {
              return delegate.size();
    public class UpShiftedChannel extends ChannelModifier { ...}
    public class DownShiftedChannel extends ChannelModifier { ... }

  • Design patterns implemented in java API

    Hi,
    I have some questions on design patterns implemented in core java class or in general in java API.
    1)Whether
    java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
    can be considered as a decorator pattern?
    2) Whether
    LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but uses them
    can be considered as a Bridge pattern?
    3) Whether Facade pattern is implemented in java ? If so which API uses it?
    4) Whether
    •     All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
    •     All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap
    can be considered as a Template method pattern?
    5) Whether
    •     java.util.Comparator#compare(), executed by among others Collections#sort()
    can be considered as a Stratergy pattern?
    6)
    Whether State pattern is implemented in java ? If so which API uses it?
    7)
    All implementations of java.lang.Runnable are considered as a Command pattern.
    8)
    Whether
    •     java.io.InputStreamReader(InputStream) (returns a Reader)
    •     java.io.OutputStreamWriter(OutputStream) (returns a Writer)
    can be considered as an Adapter pattern?
    Please clarify.
    Thanks.

    What do you think, and why?

  • Generic Proxy pattern - help needed.

    Greetings!
    Lately i have been working on some design architecture to work on possible ways of designing message flows in OSB.
    I found one excellent solution called Generic Proxy pattern at: http://javamaster.wordpress.com/tag/osb/ .
    This pattern consists of four proxy services.
    Actually Generic Proxy pattern and proxy service are different. You can read more about pattern at : http://game-engineering.blogspot.com/2010/03/adapter-pattern-vs-proxy-pattern.html
    My problem is interesting and very straight forward.
    1. I have one proxy service which is created on client side WSDL.
    2. I have one business service created on legacy system WSDL.
    Now, if i want to implement this Generic Proxy pattern, I need to create two more proxy services in between my existing proxy service & existing business service.
    On what basis should these two proxy services should be created?
    Options in OSB to create a proxy service are : WSDL Web Service / Messaging Service / Any SOAP Service / Any XML Service / Business Service / Proxy Service
    If anybody has worked in this pattern, please help.
    Any inputs from everyone are welcome.
    Thanks and Regards,
    Swapnil Kharwadkar.

    The generic proxy service will be of type "messaging service" with input/output type as text/XML.

  • Why ProfileAdapterRepository is called so? where is the Adapter in it?

    Does anyone know why ProfileAdapterRepository is called so. You won't see the word Adapter in any other repository name. Do we have an implementation of adapter pattern in ProfileRepository?
    /atg/commerce/claimable/ClaimableRepository
    /atg/commerce/inventory/InventoryRepository
    /atg/commerce/invoice/InvoiceRepository
    /atg/commerce/order/OrderRepository
    /atg/commerce/order/processor/AddOrderToRepository
    /atg/content/media/MediaRepository
    /atg/dynamo/security/AdminSqlRepository
    /atg/dynamo/service/jdbc/SDSRepository
    /atg/dynamo/service/jdbc/SQLRepository
    /atg/dynamo/templates/HTMLRepository
    /atg/dynamo/templates/XMLRepository
    /atg/multisite/SiteRepository
    /atg/sitemap/SitemapRepository
    /atg/userprofiling/PersonalizationRepository
    /atg/userprofiling/Profile*Adapter*Repository

    Sanju,
    in ATG, you can maintain separate profile repositories for external and internal users. There are separate repository definition files for internal users and external users. The external profiles are stored in the /atg/userprofiling/ProfileAdapterRepository, defined by the userProfile.xml file located in <ATG10dir>\DPS\config\profile.jar. Internal profiles are stored in the /atg/userprofiling/InternalProfileRepository, defined by the internalUserProfile.xml file in <ATG10dir>\DPS\InternalUsers\config\config.jar.
    Other repositories will not be having different categories within them. for example for inventory we do not have sub types and hence the generic term InventoryRepository. In case of profile to identify whether it is an external profile repository or internal profile repository we have additional attribute attached to the name of the repository.
    Also since Repository concept is basically built on Adapter design pattern we see this Adapter in ProfileAdapterRepository instead of something like ExternalProfileRepository

  • Which pattern for this scenario ?

    Hi all,
    I have an EJB which connects to an external system (written in Perl) using plain HttpConnections and posting HTML content.
    I would like to centralize this access using a design pattern.
    Which pattern is would fit this scenario ?
    I wonder if I should use the Adapter pattern or the Bridge Pattern.
    What do you say to it ?
    Thanks
    Francesco

    I'd kind-of guessed it was uni work :-)
    in all honesty, I wouldn't even approach the problem from a patterns perspective. all I see is a subsystem I don't want to deal with directly, so I define an interface to hide it behind. could argue that it's an Adapter, since it's taking the Http interface and abstracting away from it, to a java one. on the other hand, since mucking around with Http in java isn't exactly straight-forward, you're defining a more simple interface, so it could be considered a facade. which do you think is closer?
    most people, once au fait with design patterns, think less in terms of those patterns, and more in terms of what OO principles to apply. score some extra credit by writing a passage about how design patterns are not prescriptive, and that many coders lift ideas about encapsulation and separation from patterns, rather than use the pattern exactly as described.

  • Object oriented question

    I am sure my n00bieness is going to shine here but I have a pressing question.
    I have two classes that do a similar activity they attach some elements to an xml document and then call a web service.
    Object A uses in its method signature different object parameters then Object B does.
    For example -
    Object A{
      public ProprietaryObject doMagic(ProprietaryObject po){
        //do stuff
    Object B{
      public DiffProprietaryObject doMagic(DiffProprietaryObject po){
        //do stuff
    }There is more than one method that is similar between the two objects but this is just to get the point across.
    Anyway, Instead of creating two separate objects that do "almost" the same thing (on different object types) how can I create an elegant solution to this?
    The problem I run into is that if I create a common interface for these two object to implement the object use different proprietary objects to do their work.
    I find that I keep using the instanceof operator everywehre to determine the object type.
    Hope this is not explained to horribly...
    Any help is appreciated!

    I'd create an Interface which defines a common access method for the-operations-you-require from both proprietory classes, then implement that interface in a couple of "boundary" classes which "wrap" the proprietory classes...
    If possible, extend the disparate proprietory classes, and delegate to the appropriate methods of the "real" classes.
    If the propritory classes are final then you have to write a ship load more "boilerplate" code... every single fraggin method has to pass the buck to the appropriate method of the private instance of the "wrapped" class, and return the result... which isn't usually too bad once you roll up your sleeves and get into it.
    From memory (mine is poor) this is the essence of the [Adapter pattern|http://en.wikipedia.org/wiki/Adapter_pattern].
    Like a said, there may be quit a bit of work involved, but the advantages usually outweigh the costs... You can "refer to" the disparate proprietory classes seemlessly throughout the rest of your system... if ProprietoryClassA changes (in the next release) you can (hopefully) adapt your adapter to those changes, without having to modify all your consumer code... because it still exposes the same interface... which is the motivation for any boundary class ("Trust no one";-)
    Cheers. Keith.
    Edited by: corlettk on 8/08/2008 06:28 - Better.

  • Technical Article on Service-oriented Integration Using JBI Posted

    I've just posted an article on the open-esb site about using JBI for what we have come to call service-oriented integration: enterprise integration atop a SOA fabric. The article includes an example of a simple adapter pattern implementation that includes message transformation and protocol hopping.
    See https://open-esb.dev.java.net/ for the PDF download.

    At last!!
    Finally an article about the real JBI and what JBI is all about. I don't know what's going on with people's understanding of JBI.
    At JavaOne, I remember one of the expert group, from Oracle I think, proudly claiming that JBI will be one of the core architectures that companies will be delivering their integration business upon. Now I wonder where Oracle's, SAP's and IONA's contributions are so far. Oracle for example really contributed to JSR 208 by marketing and implementing SCA.
    Although in early stages, I think open source implementations are missing the point as well. Using open source implementation X, I couldn't see a scenario that shows the power of the concept, while implementation Y just did not like service units, service connections and link types, then tried to invent its own configuration and routing descriptors, wasting very valuable time.
    Anyway, may be one just have to wait and see!!
    Thanks Ron for such contribution.

  • Extending factory-made class

    A library, for instance JDK core APIs, usually offers instances of internal concrete class. For users
    of the library, the class is usually given as an abstract class. Some of them may or may not have static factory method that delivers a concrete class instance. For example, FileSystemView has
    and Graphics hasn't. The difference is not important for the problem of this thread.
    We can get those concrete class by calling Object#getClass() method. But how could we extend
    the class and override just one or two methods for trivial, but important, customization? In other
    words, we'd like to use a major part of the implementation as is, not implementing the abstract
    class from scratch.

    We can get those concrete class by calling
    Object#getClass() method. But how could we extend
    the class and override just one or two methods for
    trivial, but important, customization? In other
    words, we'd like to use a major part of the
    implementation as is, not implementing the abstract
    class from scratch.I'm not sure I fully understand what you want to do but I think you could use the idea behind the Adapter pattern. You create an adapter class with the public interface you want and then you use an object of the class you want to customize (the adptee) to implement that adapter class.
    Most adapter class methods will just call the corresponding methods of the adaptee but some are implemented differently.

  • Question about creating Jtable from a "Self Made" object.

    Hi all,
    I am new to java and this is my first post here.
    First of all, i want to say nice to meet u all. This is a blessed forum, and it already helped me a lot.
    I hope that i will be clear with my question.
    Now to the question:
    I have created a class that reads parameter file and its meta file and combine them (each parameter in the file gets its properties such as "Mask", "Default" and else from the meta file) to one object (the class creates collection of instance of it self that has a get method.
    the class also has method that get "Column Names" from the instance.
    I want to create a Jtable that will present these parameter(each row will present 1 parameter).
    Only the second column should be editble and it should choose the editor by the type of data (example: if it is boolean should get a check box, i has more than one "ValidValue" should get a combo box and so on).
    What would be the best way to do that?
    I am not looking for a source code, I am looking for concept suggestion.
    This project is for "Self Learning" porpuse, and any help will be gratitude.
    Thanks a lot you all,
    On Katalan.

    Use the Adapter pattern (http://en.wikipedia.org/wiki/Adapter_pattern) to wrap your object as a TableModel.
    eg, if your data class is "ParameterSet" you might do this...
    public class ParameterSetTableModel implements TableModel
        private final ParameterSet set;
        public ParameterSetTableModel(ParameterSet set)
            this.set = set;
        public String[] getColumnNames()
            return this.set.getColumnNames();
        // you'll need to implement all TableModel methods, either
        // directly calling the wrapped object or calling it and
        // converting the data, or whatever's appropriate
    }

  • Design for two interacting, extensible classes

    Hi,
    I have a design problem where I have two interacting classes that both need to be highly extensible. I'm pretty sure this not an uncommon problem but I can't really seem to find an appropriate pattern to implement it.
    The problem comes from the field of reinforcement learning, where an Agent learns some task in an Environment by executing Actions based on the current State of the environment. The State has to be provided by the Environment, and the Action chosen by the Agent based on that State has to be executed on the Environment. I thus have an Environment interface (for multi-agent problems) like so:
    public interface Environment {
         //execute given action for given agent (e.g., move the agent, let the agent pick up smth
            //in the env, etc), and return a reward
         public double executeAction( Action act, Agent a );
         //compute and return state of given agent (e.g., what the agent can currently see in the
           //environment)
         public State getState( Agent a );
    }There can be many different types of environments, and many different types of actions. So I thought of having a callback method on the Action that the Environment calls in method executeAction, like:
    public interface Action {
         //execute on the given environment for the given agent
         public void execute(Environment env, Agent a);
    }In that case you could have the same environment (e.g., a world with blocks), and different actions (say move, push a block away, pick up a block, etc). Does this make any sense? It's a little like the Command pattern perhaps?
    There are two things I'm worried about. One is that the Action would need to cast the received Environment to the right implementation, but I guess that's unavoidable. The other (actually two) is that the Environment implementation would need to expose the right methods for the action to be able to execute, plus I don't always want an Action to be able to do anything it wants with the environment (e.g. teleport the agent, remove all obstacles). On the other hand maybe I shouldn't worry about the latter since it's just meant to be a toolkit, so if people using it want to program actions to teleport the agent, that's their business.
    Any suggestions/comments greatly appreciated.
    Thanks
    Matt

    I am not a native english speaker, and I'm not sure I understand your description. Is the following pseudo-code a correct description of your design?No problem, me neither. Maybe that's why it was hard to understand :) Actually, an agent should by no means have direct access to the environment: it is only allowed to perceive things through the State object it receives. So the design is something like:
    public interface Agent {
            //do a step: choose an action based on the current state, and learn from
            //the reward received after the last action.
         public Action doStep( State s, double reward );
    public class Simulator {
            //do one simulation step
         public void doStep() {
              State s;
              Action act;
              for ( Agent a : agents ) {
                            //get the agent's state from the environment
                   s = env.getState(a);
                            //let the agent choose an action based on that state (lastReward is stored in a Map, omitted)
                   act = a.doStep(s, lastReward);
                            //execute action on the environment and store the reward for this agent
                   lastReward = env.executeAction(act, a));
    There are two things I'm worried about. One is that the Action would need to cast the received Environment to the right implementation, but I guess that's unavoidable.Why? Cant he environment interface define abstract "modifier" methods that make sense to all implementations?Not really. An environment can be anything: a world with objects that the agent has to collect/avoid (I chose that example because I thought it might be easy to visualise and understand). A Blackjack game in which the agent has to choose to get another card or stop. The stock market in which the agent has to make trading decisions. And so on.
    And iff the actions are specific to some environment implementations, then each environment can implement executeAction his way, for example calling different Action methods. In this case the Action become merely a Visitor.Yes, I indeed looked at the Visitor pattern, but I think it's not flexible enough. The types of the environments / actions need to be known beforehand, and in my case they can be anything.
    The other (actually two) is that the Environment implementation would need to expose the right methods for the action to be able to execute, plus I don't always want an Action to be able to do anything it wants with the environment (e.g. teleport the agent, remove all obstacles).Method executeAction should use only those methods exposed in interface Environment (which is the type of the env argument).
    If the Action and Agent implementations need some different views of the environments, just define two different interfaces.Hmm, yes. The problem is that the Environment interface should pretty much only specify those methods that I listed. Those are the methods necessary for the reinforcement learning paradigm (basically as implemented in the Simulator). Adding additional, problem-specific methods to that interface would not make sense, because environments can be anything. But, perhaps I could do something like:
    public interface BlockWorld {
         public boolean move(Block b);
         public Block getBlockAt(int x, int y);
    public class SomeWorld implements Environment, BlockWorld {}
    public class PushAction implements Action {
         @Override
         public void execute(Environment env, Agent a) {
                    //unavoidable (?) cast
              BlockWorld world = (BlockWorld) env;
              //get the block that the agent is facing, and move it
              //as specified in the action
    }So define an interface according to the methods the world wants to expose. The only concern is that the same world (with obstacles and what not) could be used in a lot of different contexts, and I guess it's not desirable to subclass it every time just to make it implement an additional interface because one wants to expose different methods. But maybe I can use the Adapter pattern for this?

  • Jtree examples of populating data from database

    I have searched many of the solutions here, but the threads that contain examples of jtree loading from an sql database are not available. Does anyone have a good example of populating a jTree from the database?
    Thank You

    Hi,
    AFAIK, there is no direct approach to populate a JTree directly from a resultset. However, JTree can use a DOM tree as its model by using the adapter pattern. The procedure to do this is well-documented in the SUN website and the link is provided below. The code to convert a resultset to XML is provided below:
    protected void resultSetToXML(OutputStream out,
    ResultSet rs,
    String stylesheet)
    throws IOException, ServletException {
    // Create reader and source objects
    SqlXMLReader sxreader = new SqlXMLReader();
    SqlInputSource sis = new SqlInputSource(rs);
    // Create SAX source and StreamResult for transform
    SAXSource source = new SAXSource(sxreader, sis);
    StreamResult result = new StreamResult(out);
    // Perform XSLT transform to get results. If "stylesheet"
    // is NULL, then use identity transform. Otherwise, parse
    // stylesheet and build transformer for it.
    try {
    // Create XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;
    if (stylesheet == null) {
    t = tf.newTransformer();
    } else {
    // Read XSL stylesheet from app archive and wrap it as
    // a StreamSource. Then use it to construct a transformer.
    InputStream xslstream = _config.getServletContext().
    getResourceAsStream(stylesheet);
    StreamSource xslsource = new StreamSource(xslstream);
    t = tf.newTransformer(xslsource);
    // Do transform
    t.transform(source, result);
    } catch (TransformerException tx) {
    throw new ServletException(tx);
    The classes SQLXMLReader and other classes used in this example are available in the following java packages.
    import java.sql.*;
    import javax.sql.DataSource;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.sax.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.AttributesImpl;
    The following is the link that explains how to load a JTree from DOM.
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM6.html
    Cheers,
    vidyut

Maybe you are looking for

  • HT201272 Some of my previous purchases aren't showing up on the iTunes store. It says "Purchased" but won't let me download them. Is there any way to fix this?

    I've been making my iTunes music purchases on my iPhone for over a year now. I bought a new one so I relied on iCloud to keep my purchases on record. When downloading my songs, I saw that some of them were missing. When I logged into the iTunes store

  • 24" IMAC Display Too Bright

    I am still doing DD on changing from WinTel to Apple. I have viewed both the 20 inch and 24 inch models at a local reseller. I have heard of several complaints that the 24" is too bright. Is there any validity to this complaint? Can the Brightness be

  • AE5.2:Automatic ESS User Set up and email notification to the User

    Forum, In AE, stageless ESS user set up creates the ESS user and sends an email to new user like below... This is to inform you that your request REQUESTNUMBER provisioning has been done. Your account has been created. Please find the information bel

  • How to set up

    I have a 500GB HD connected to my TC via USB. I can access the external HD via the airport extreme feature. But the real reason why I got the 500GB is because I want to make that external HD the primary location for my iTunes library. I wanted to kno

  • MDM not connecting to Oracle.

    HI Everyone, MDM 7.1 SP06 with Oralce 11g on Windows Server 2008 R2 Environment Recently we have moved our MDM server from one location to another location (i.e) data center shift. After this move, we were not able to connect MDM, this issue has been