Hello!
Below is a small program using the adaptor pattern.
We have four classes these are: PegAdapter, RoundPeg, SquarePeg
and a class TestPegs acting like a client
In class PegAdapter has some text just above the class header saying
"Its adapts a RoundPeg to a SquarePeg".
In the class that acts as a client which isTestPegs
Just above this class definition of this TestPegs we have some text here
saying
"The solution: create an adapter that adapts a square peg to a round peg!"
Now to my question: It's all about understand the meaning of these two rows?
"Its adapts a RoundPeg to a SquarePeg".
"The solution: create an adapter that adapts a square peg to a round peg!"
The first row is some kind of documentation for class PegAdapter and
the second row is some kind of documentation for class isTestPegs
How can they say in the first row that Its adapts a RoundPeg to a SquarePeg
and in the second row say adapts a square peg to a round peg.
Why is it different?
The row "adapts a RoundPeg to a SquarePeg" is the other way around compared
to row
"adapts a square peg to a round peg"
What is it that decide whether it should be "adapts a RoundPeg to a
SquarePeg" or
"adapts a square peg to a round peg"
public class RoundPeg
{
public void insertIntoHole(String msg)
{ System.out.println("RoundPeg insertIntoHole() : " + msg); }
}
/* Its adapts a RoundPeg to a SquarePeg */
public class PegAdapter extends SquarePeg
{
private RoundPeg roundPeg;
public PegAdapter(RoundPeg peg)
{ this.roundPeg = peg; }
public void insert(String str)
{ roundPeg.insertIntoHole(str); }
}
public class SquarePeg
{
public void insert(String str)
{ System.out.println("SquarePeg insert() : " + str); }
}
// Now we'd like to do an insert using the round peg.
// But this client only understand the insert()
// method of pegs, not a insertIntoHole() mothod.
// The solution: create an adapter that adapts
// a square peg to a round peg!
public class TestPegs
{
public static void main(String args[] )
{
RoundPeg roundPeg = new RoundPeg ();
SquarePeg squarePeg = new SquarePeg ();
squarePeg.insert("Inserting square peg . . .");
PegAdapter adapter = new PegAdapter (roundPeg);
adapter.insert("Inserting round peg . . .");
}
}
//Tony