Open main menu

CDOT Wiki β

Changes

Adapter

6,548 bytes added, 16:11, 27 March 2007
Object Adapter Pattern
There are two specific types of adapter patterns - ''object adapter pattern'' and ''class adapter pattern''. The latter uses multiple inheritance whereas the former uses an instance of the reuseable class it wants to adapt. Between the two, object adapter pattern is the favored one due to the fact that popular languages such as Java do not support multiple inheritance.
== Object Adapter Pattern ==
This adapter pattern uses an instance of the class it wraps. By using an instance, methods belonging to the wrapped object can be invoked.
[[Image:objectadapter_diag_rueen2.GIF]]
== Class Adapter Pattern ==
This adapter pattern uses multiple inheritance as a means to wrap the reusable class and use its functionality.
== Code Examples ==
'''Java'''
The following Adapter pattern code example is from FreeMind - GNU General Public License. FreeMind's [http://dofactorywww.google.com/Patternscodesearch?hl=en&q=show:SSjMlfyYK2U:RCv_23t_s7k:tpy_iiX4ncI&sa=N&ct=rd&cs_p=http://gentoo.osuosl.org/distfiles/freemind-src-0_7_1.tar.gz&cs_f=freemind/freemind/PatternAdaptermodes/ArrowLinkAdapter.java File Repository]  Explanation: In this example, an ArrowLinkAdapter is created to be used to adapt different arrow shaped links in FreeMind's MindMap area. ArrowLinkAdapter.java is the '''Adapter''' and LinkAdapter.java is the '''Adaptee'''. Even though LinkAdapter is an adapter itself, it is infact the adaptee in this case.   '''ArrowLinkAdapter.aspxjava'''
<pre>
using System/*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2001 Joerg Mueller <joergmueller@bigfoot.com> *See COPYING for Details * *This program is free software;you can redistribute it and/or *modify it under the terms of the GNU General Public License *as published by the Free Software Foundation; either version 2 *of the License, or (at your option) any later version. * *This program is distributed in the hope that it will be useful, *but WITHOUT ANY WARRANTY; without even the implied warranty of *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *GNU General Public License for more details. * *You should have received a copy of the GNU General Public License *along with this program; if not, write to the Free Software *Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *//*$Id: ArrowLinkAdapter.java,v 1.4 2003/12/07 21:00:19 christianfoltin Exp $*/
namespace DoFactorypackage freemind.GangOfFourmodes;import freemind.Adaptermodes.RealWorldLinkAdapter;{import freemind.main.FreeMindMain;
// MainApp test application import java.awt.Point;
public abstract class MainApp ArrowLinkAdapter extends LinkAdapter implements MindMapArrowLink { static void Main() { // Non-adapted chemical compound Compound stuff = new Compound("Unknown"); stuff.Display(); // Adapted chemical compounds Compound water = new RichCompound("Water"); water.Display();
Compound benzene = new RichCompound("Benzene") /** the zero is the start point of the line;*/ benzene.Display() protected Point startInclination; /** the zero is the start point of the line;*/ protected Point endInclination; protected String startArrow; protected String endArrow;
Compound alcohol = new RichCompound("Alcohol");
alcohol.Display();
// Wait for user public ArrowLinkAdapter(MindMapNode source,MindMapNode target,FreeMindMain frame) { Console.Read super(source, target, frame, "standardlinkcolor", "standardlinkstyle"); startArrow = "None"; endArrow = "Default";
}
}
// "Target" public Point getStartInclination() { return startInclination; } public Point getEndInclination() { return endInclination; } public String getStartArrow() { return startArrow; } public String getEndArrow() { return endArrow; }
class Compound public void setStartInclination(Point startInclination) { this.startInclination=startInclination; } public void setEndInclination(Point endInclination) { this.endInclination=endInclination; } protected string namepublic void setStartArrow(String startArrow) { if(startArrow == null || startArrow.toUpperCase().equals("NONE")) { this.startArrow = "None"; return; } else if(startArrow.toUpperCase().equals("DEFAULT")) { this.startArrow = "Default"; return; } // dont change: System.err.println("Cannot set the start arrow type to " + startArrow); protected float boilingPoint} public void setEndArrow(String endArrow) { if(endArrow == null || endArrow.toUpperCase().equals("NONE")) { this.endArrow = "None"; protected float meltingPoint return; } else if(endArrow.toUpperCase().equals("DEFAULT")) { this.endArrow = "Default"; return; protected double molecularWeight } // dont change: System.err.println("Cannot set the end arrow type to " + endArrow); protected string molecularFormula;}
public Object clone() { ArrowLinkAdapter arrowLink = (ArrowLinkAdapter) super.clone(); // Constructor now replace the points: arrowLink.startInclination = (startInclination==null)?null:new Point(startInclination.x, startInclination.y); public Compound arrowLink.endInclination = (endInclination==null)?null:new Point(string nameendInclination.x, endInclination.y); { arrowLink.startArrow = (startArrow==null)?null:new String(startArrow); this arrowLink.name endArrow = (endArrow= name=null)?null:new String(endArrow); return arrowLink;
}
public virtual void Display()} { Console.WriteLine("\nCompound: {0} ------ ", name);</pre> } }'''LinkAdapter'''
<pre>/*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2001 Joerg Mueller <joergmueller@bigfoot.com> *See COPYING for Details * *This program is free software; you can redistribute it and/or *modify it under the terms of the GNU General Public License *as published by the Free Software Foundation; either version 2 *of the License, or (at your option) any later version. * *This program is distributed in the hope that it will be useful, *but WITHOUT ANY WARRANTY; without even the implied warranty of *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *GNU General Public License for more details. * *You should have received a copy of the GNU General Public License *along with this program; if not, write to the Free Software *Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *//*$Id: LinkAdapter.java,v 1.3 2003/11/29 17:12:33 christianfoltin Exp $*/ "Adapter"
class RichCompound : Compoundpackage freemind.modes; {import freemind.modes.LineAdapter; private ChemicalDatabank bankimport freemind.main.FreeMindMain;
// Constructor public RichCompound(string name) : base(name) abstract class LinkAdapter extends LineAdapter implements MindMapLink { }
public override void Display()String destinationLabel; { // Adaptee bank = new ChemicalDatabank()String referenceText; boilingPoint = bank.GetCriticalPoint(name, "B"); meltingPoint = bank.GetCriticalPoint(name, "M"); molecularWeight = bank.GetMolecularWeight(name); molecularFormula = bank.GetMolecularStructure(name) MindMapNode source;
base.Display public LinkAdapter(MindMapNode source,MindMapNode target,FreeMindMain frame); { Console.WriteLine this(" Formula: {0}"source,target, molecularFormula); Console.WriteLine(" Weight : {0}"frame, molecularWeight); Console.WriteLine(" Melting Pt: {0}standardlinkcolor", meltingPoint); Console.WriteLine(" Boiling Pt: {0}standardlinkstyle", boilingPoint);
}
}
/** For derived classes.*/ "Adaptee" protected LinkAdapter(MindMapNode source,MindMapNode target,FreeMindMain frame, String standardColorPropertyString, String standardStylePropertyString) { super(target, frame, standardColorPropertyString, standardStylePropertyString); this.source=source; destinationLabel = null; referenceText = null; }
class ChemicalDatabank public String getDestinationLabel() {return destinationLabel; } // The Databank 'legacy API' public String getReferenceText(){ return referenceText; } public float GetCriticalPointMindMapNode getSource(string compound, string point) { float temperature = 0.0Freturn source;}
// Melting Point if public void setSource(point == "M"MindMapNode source) {this.source=source;} switch (compound.ToLower public void setDestinationLabel(String destinationLabel)) { case "water" : temperature = 0this.0F; break; case "benzene" : temperature = 5.5F; break; case "alcohol" : temperature destinationLabel = -114.1FdestinationLabel; break; } } // Boiling Point else { switch (compound.ToLower public void setReferenceText(String referenceText)) { case "water" : temperature = 100this.0F; break; case "benzene" : temperature referenceText = 80.1FreferenceText; break; case "alcohol" : temperature = 78.3F; break; } } return temperature; }
// public string GetMolecularStructureObject clone(string compound){// try { // return super.clone();// } catch(java.lang.CloneNotSupportedException e) { string structure = ""// return null;// }// }
switch (compound.ToLower())
{
case "water" : structure = "H20"; break;
case "benzene" : structure = "C6H6"; break;
case "alcohol" : structure = "C2H6O2"; break;
}
return structure;
}
public double GetMolecularWeight(string compound)
{
double weight = 0.0;
switch (compound.ToLower())
{
case "water" : weight = 18.015; break;
case "benzene" : weight = 78.1134; break;
case "alcohol" : weight = 46.0688; break;
}
return weight;
}
}
}
 
</pre>
----'''C++''' KDEBluetooth - GNU General Public License KDEBluetooth [http://www.google.com/codesearch?hl=en&q= References show:SWkEw1PFvDM:seiYnh_fPLA:RjuqBeXZiEM&sa=N&ct=rd&cs_p=http://members.xoom.alice.it/motaboy/kdebluetooth-20040128.tar.bz2&cs_f=kdebluetooth-20040128/libkbluetooth/adapter.h File Repository] '''adapter.h''' <pre>//-*-c++-*-/*************************************************************************** * Copyright (C) 2003 by Fred Schaettgen * * kdebluetooth@0xF.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #ifndef BTADAPTER_H#define BTADAPTER_H #include <vector>#include <qstring.h>#include <qvaluevector.h>#include "deviceaddress.h" namespace KBluetooth{ /** Class representing a local bluetooth adapter. * This class provides access to the properties of a local bluetooth * adapter. This class has no public constructors. You can get the * list of available adapters using KBluetooth::Adapters. */class Adapter{ friend class Adapters;public: enum ConnectionType { SCO = 0, ACL = 1 }; enum ConnectionState { NOT_CONNECTED, CONNECTED, CONNECTING, UNKNOWN_STATE }; struct ConnectionInfo { DeviceAddress address; int handle; ConnectionType type; ConnectionState state; bool out; uint link_mode; }; typedef QValueVector<ConnectionInfo> ConnectionInfoVector;  /** Returns the device address of the given adapter. @return The device address */ DeviceAddress getAddress() const;  /** Returns the name of the adapter. @return The device name */ QString getName() const;  /** Returns the index of the device. @return device index */ int getIndex() const;  /** Return a deviceaddress for each ACL-Connection */ ConnectionInfoVector getAclConnections() const;  ConnectionState getAclConnectionState(const DeviceAddress& addr) const; protected: /** Constructor used internally by KBluetooth::Adapters. */ Adapter(int index, const DeviceAddress& address, QString nameStr);private: int index; QString nameStr; DeviceAddress address;};  /** Enumerates the locally attached bluetooth devices. * The information in this class stays static until update() * is called. */class Adapters{public: /** Default constructor. Calls update(). */ Adapters();  /** Gets the number of adapters. @return number of adapters */ int count();  /** Returns a single adapter @param n index of the adapter (0 <= n < count()) @return adapter info */ const Adapter& operator[](int n) const;  /** Refreshes the list of adapters. */ void update();private: std::vector<Adapter> adapters; static int dev_info(int s, int dev_id, long arg); void dev_info(int s, int dev_id);}; } #endif  </pre>
== Other ==
1
edit