//
Purpose.?Chain of Responsibility and
Command demo
//
// Chain of Responsibility -
// 1. Base class
maintains a "next" pointer
// 2. Each "node" object
evaluates each request
// 3. Node object may pass on a request to
the
//牋?next node
// 4.
Client "launches and leaves" each request
//
// Command
-
// 5. Base class specifies an "execute" method
// 6.
Derived classes call a method on an object
import java.awt.*;
public
class CommandChainDemo {
牋
interface Command {
牋牋?
public void execute( Component c );牋牋牋牋牋牋牋牋牋牋牋牋牋 //// 5 \\\\
牋 }
牋
static class Back implements Command {
牋牋?private Color color;
牋牋?public Back( Color c )牋牋牋牋牋牋 { color = c; }
牋牋?public void execute( Component c ) { c.setBackground( color
); }?// 6 \\
牋 }
牋
static class Fore implements Command {
牋牋?private Color color;
牋牋?public Fore( Color c )牋牋牋牋牋牋 { color = c; }
牋牋?public void execute( Component c ) { c.setForeground( color
); }
牋 }
牋 static class ChainNode extends Button
{
牋牋 ?/span>private ChainNode next;牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋 //// 1 \\\\
牋牋?public ChainNode( String name, ChainNode
nx ) {
牋牋牋牋 super( name
);
牋牋牋牋 setFont( new Font(
"SansSerif", Font.BOLD, 30 ) );
牋牋牋牋 next = nx;
牋牋?
}
牋牋?public void process(
Command cmd ) {
牋牋牋牋
cmd.execute( this );牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋 //// 2 \\\\
牋牋牋牋 if (next != null) next.process( cmd
);牋牋牋牋牋牋牋牋牋牋 //// 3 \\\\
牋 }?
}
牋 public static
ChainNode createChain( Frame f ) {
牋牋?
ChainNode last牋 = new ChainNode(
"third",?null );
牋牋?ChainNode middle = new ChainNode(
"second", last );
牋牋?
ChainNode first?= new ChainNode(
"first",?middle );
牋牋?f.add( first );?f.add( middle );?f.add( last );
牋牋?
return first;
牋 }
牋 public static void main( String[] args )
{
牋牋?Frame f = new Frame(
"ChainCommandDemo" );
牋牋?
f.setLayout( new FlowLayout() );
牋牋?ChainNode root = createChain( f );
牋牋?f.pack();
牋牋?f.setVisible( true );
牋牋?Command[] cmds = { new Back( Color.cyan
),牋 new Fore( Color.blue),
牋牋牋牋牋牋牋牋牋牋牋牋 new Back(
Color.yellow ), new Fore( Color.red)牋
};
牋牋?for (int i=0; i
< cmds.length; i++) {
牋牋牋牋
Read.aString();
牋牋牋牋
root.process( cmds[i] );牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋牋 //// 4 \\\\
}?}?
}