Reputation: 19642
I am trying to Implement a doubly linked with null objects at the beginning and end of the list using null object design pattern. So an empty list will contain two null objects. So I wrote this code Does this follow null object design pattern? If not how can I achieve that. ANy suggestions will be appreciated.
Updated Code-
// Creating a doubly linked list.
doubleLinkedList = new DoubleLinkedList();
class DoubleLinkedList {
private NewLink firstNode;
private NewLink lastNode;
private NewLink rootNode;
public DoubleLinkedList() {
//So this satisfies my question that I have asked meaning null objects at beginning and last node or something else I have to do.
firstNode = NewLink.NULL_NODE;
lastNode = NewLink.NULL_NODE;
}
}
class NewLink {
public String data;
public NewLink nextPointer;
public NewLink previousPointer;
public static final NewLink NULL_NODE = new NewLink();
public NewLink(String id) {
data = id;
}
public NewLink() {
}
// Overriding toString method to return the actual data of the node
public String toString() {
return "{" + data + "} ";
}
}
Upvotes: 0
Views: 779
Reputation: 29741
public static final NewLink NULL_NODE = new NewLink();
must be in NewLink
class
so
firstNode = NewLink.NULL_NODE;
secondNode = NewLink.NULL_NODE;
also you can make all methods from NewLink
- abstract
and make two nested classes: for NULL objects and for not NULL object.
It's can be very helpful in difficult situations
Upvotes: 1
Reputation: 5330
We use Null object design pattern if we want to assign some default behaviors (or prevent some behaviors to happen as a default behavior) For example using Null object pattern we can replace this code :
if(myObj!=null)
myObj.DoSomething();
else
DoSomethingElse();
wtih this one:
myObj.DoSomething() //assuming that myObj can be a Null object (not a null reference) that has implemented DoSomethingElse when you ask it to DoSomething()
Thus a Null Object design pattern actually uses a default object reference (not a null reference )
Upvotes: 2
Reputation: 47403
No, your code doesn't implement Null Object Design Pattern
. Its essence is not to use null
but to create an object which will represent the null
.
For example:
public static final NewLink NULL_NODE = new NewLink();
And then:
firstNode = NULL_NODE;
lastNode = NULL_NODE;
Upvotes: 4