Premium Partner

Software Construction: Design Patterns 2

Cards to learn the design patterns

Cards to learn the design patterns


Kartei Details

Karten 7
Sprache Deutsch
Kategorie Informatik
Stufe Universität
Erstellt / Aktualisiert 28.12.2019 / 11.01.2020
Lizenzierung Keine Angabe
Weblink
https://card2brain.ch/box/20191228_software_construction_design_patterns_2
Einbinden
<iframe src="https://card2brain.ch/box/20191228_software_construction_design_patterns_2/embed" width="780" height="150" scrolling="no" frameborder="0"></iframe>

The Command Pattern (Definition)

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

Class Diagram of Command Pattern

Client: The Client is responsible for creating a ConcreteCommand and setting its Receiver (=Light in example) (testSimpleRemoteControl in example).

Invoker: The Invoker holds a command and at some point asks the command to carry out a request by calling its execute() method (SimpleRemoteControl in example).

Receiver: The Receiver knows how to perform the work needed to carry out the request (Light in example). Any class can act as a Receiver. 

Command: Command declares an interface for all commands. As you already know, a command is invoked through its execute() method, which asks a receiver to perform an action (Command interface in example).

ConcreteCommand: The ConcreteCommand (LightCommandOn in example) defines a binding between an action and a Receiver. The Invoker makes a request by calling execute() and the ConcreteCommand carries it out by calling one or more actions on the Receiver.

Command Pattern with Undo Code Example

Command Pattern Queuing Requests

Command Pattern Logging Requests

The State Pattern (Definition)

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Class Diagram of State Pattern

Context: The Context is the class that can have a number of internal states. In our example, the GumballMachine is the Context.

Whenever the request() is made on the Context it is delegated to the state to handle.

State: The State interface defines a common interface for all concrete states; the states all implement the same interface, so they are interchangeable.

ConcreteStates: ConcreteStates handle requests from the Context. Each ConcreteState provides its own implementation for a request. In this way, when the Context changes state, its behavior will change as well.