Changed package naming across all examples.

This commit is contained in:
Ilkka Seppala
2015-05-31 11:55:18 +03:00
parent 703ebd3e20
commit 8524c75ba6
437 changed files with 1095 additions and 1402 deletions

View File

@ -0,0 +1,32 @@
package com.iluwatar.nullobject;
/**
*
* Null Object pattern replaces null values with neutral objects.
* Many times this simplifies algorithms since no extra null checks
* are needed.
*
* In this example we build a binary tree where the nodes are either
* normal or Null Objects. No null values are used in the tree making
* the traversal easy.
*
*/
public class App
{
public static void main( String[] args ) {
Node root = new NodeImpl("1",
new NodeImpl("11",
new NodeImpl("111",
NullNode.getInstance(),
NullNode.getInstance()),
NullNode.getInstance()),
new NodeImpl("12",
NullNode.getInstance(),
new NodeImpl("122",
NullNode.getInstance(),
NullNode.getInstance())));
root.walk();
}
}

View File

@ -0,0 +1,15 @@
package com.iluwatar.nullobject;
/**
*
* Interface for binary tree node.
*
*/
public interface Node {
String getName();
int getTreeSize();
Node getLeft();
Node getRight();
void walk();
}

View File

@ -0,0 +1,50 @@
package com.iluwatar.nullobject;
/**
*
* Implementation for binary tree's normal nodes.
*
*/
public class NodeImpl implements Node {
private final String name;
private final Node left;
private final Node right;
public NodeImpl(String name, Node left, Node right) {
this.name = name;
this.left = left;
this.right = right;
}
@Override
public int getTreeSize() {
return 1 + left.getTreeSize() + right.getTreeSize();
}
@Override
public Node getLeft() {
return left;
}
@Override
public Node getRight() {
return right;
}
@Override
public String getName() {
return name;
}
@Override
public void walk() {
System.out.println(name);
if (left.getTreeSize() > 0) {
left.walk();
}
if (right.getTreeSize() > 0) {
right.walk();
}
}
}

View File

@ -0,0 +1,44 @@
package com.iluwatar.nullobject;
/**
*
* Null Object implementation for binary tree node.
*
* Implemented as Singleton, since all the NullNodes are the same.
*
*/
public class NullNode implements Node {
private static NullNode instance = new NullNode();
private NullNode() {
}
public static NullNode getInstance() {
return instance;
}
@Override
public int getTreeSize() {
return 0;
}
@Override
public Node getLeft() {
return null;
}
@Override
public Node getRight() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public void walk() {
}
}