code to explanationWed, 28 Dec 2022

class TestCommand { public static void main(String[] args) { DvdName jayAndBob = new DvdName("Jay and Silent Bob Strike Back"); DvdName spongeBob = new DvdName("Sponge Bob Squarepants - " + "Nautical Nonsense and Sponge Buddies"); System.out.println("as first instantiated"); System.out.println(jayAndBob.toString()); System.out.println(spongeBob.toString()); CommandAbstract bobStarsOn = new DvdCommandNameStarsOn(jayAndBob); CommandAbstract bobStarsOff = new DvdCommandNameStarsOff(jayAndBob); CommandAbstract spongeStarsOn = new DvdCommandNameStarsOn(spongeBob); CommandAbstract spongeStarsOff = new DvdCommandNameStarsOff(spongeBob); bobStarsOn.execute(); spongeStarsOn.execute(); System.out.println(" "); System.out.println("stars on"); System.out.println(jayAndBob.toString()); System.out.println(spongeBob.toString()); spongeStarsOff.execute(); System.out.println(" "); System.out.println("sponge stars off"); System.out.println(jayAndBob.toString()); System.out.println(spongeBob.toString()); } }

This example includes a number of classes to illustrate the command pattern. The DvdName object has the behavior of displaying its name in the requested format. The DvdCommandNameStarsOn and DvdCommandNameStarsOff objects have the behavior of calling the starsOn and starsOff methods on the DvdName object they were instantiated with. The CommandAbstract is the abstract class with the execute method. The execute method is called on the concrete command objects.

Questions about programming?Chat with your personal AI assistant