Null Object design mode

zhaozj2021-02-16  49

Null Object Pattern

intention

Provide an object [such as a proxy] to give a given type to replace this object empty. Null Object provides clever, nothing, hiding details from its partners.

Alias

Stub, Active Nothing

motivation

Sometimes, a class requires a partner that it doesn't need to do anything. However, class expects to treat one [what does not do] has the same method with the behavior provided by the actual object.

For example, consider a problem that displays the ball to move the screen and there is a special color effect. This can be achieved by creating a ball to display the ball and using a STRATEGY PATTERN [GHJV95, page 315]. However, the simplest strategy that you want to produce is that the simplest strategy that is possible is working.

The simplest strategy is not a policy. That is do Nothing, not moving and does not change the color. However, Strategy Pattern requires the ball with the object that implements STRATEGY. This is a useful place for NULL OBJECT mode. Just simply realize NullMovementStrategy classes that do not move the ball and Nullcolorstrategy classes that do not change the color of the ball. Both of these can achieve no code in nature. All methods are only "Nothing" in these classes. They are the perfect example of Null Object mode.

The key to Null Object mode is an abstract class that defines the interface for all objects of this type. NULL Object is achieved by subclass of this abstraction. So it follows the interface of the abstraction, which can be used anywhere in this class. A value that compares "NULL" that is specifically implemented using an image that does not actually realizes an abstract interface and must be inspected as a particular code in any object using an abstract interface.

Generally, NULL Objects will be too simple and "stupid", but in fact, a null objects always knows what to do if there is no other object impact. Therefore, in fact it is the most "intelligence".

applicability

Use Null Object mode in the following situations

An object requires a partner. Null Object will not be introduced into this partner system - it utilizes the already existing collaborators.

Some partners should not do anything.

Formation

Participant

Client

Need a partner

AbstractObject

Declare the interface of the Client partner

Appropriate interface default behavior in all classes

RealObject

Define a subclass of AbstractObject, which implements useful behavior for Client expected

Define a specific subclass of AbstractObject to provide customer expected useful behavior

Nullobject

Provide an interface consistent with AbstractObject, so that this empty object can replace true objects

Make the method "do nothing" in the interface

When more than one method "do nothing" is required, the same number of empty objects is needed.

转载请注明原文地址:https://www.9cbs.com/read-23467.html

New Post(0)