[Design Pattern] Verhaltensmuster: Null Object


Thomas Darimont

Premium-User
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Null Object

Java:
package de.tutorials.design.patterns.misc;

import org.jpatterns.gof.SingletonPattern.Singleton;
import org.jpatterns.plopd.NullObjectPattern.NullObject;

public class NullObjectExample {
	public static void main(String[] args) {
		CustomerRepository cr = new CustomerRepository();
		
		for(int i = 0; i < 10;i++){
			Customer c = cr.getCustomer(i);
			System.out.println(c.getName() + " " + c.isNull());
		}
		
	}

	static class CustomerRepository{
		public Customer getCustomer(int id){
			Customer c = loadCustomer(id);
			return c == null ? NullCustomer.INSTANCE : c; 
		}

		private Customer loadCustomer(int id) {
			return id % 3 != 0 ? new Customer(""+id) : null;
		}
	}
	
	static interface Nullable{
		boolean isNull();
	}
	
	static class Customer implements Nullable{
		private final String name;
		
		public Customer(String name) {
			this.name = name;
		}

		@Override
		public boolean isNull() {
			return false;
		}
		
		public String getName(){
			return this.name;
		}
		
		@Override
		public String toString() {
			return getClass().getSimpleName()+": " + this.name;
		}

	}
	
	@Singleton
	@NullObject
	static class NullCustomer extends Customer{

		private final static Customer INSTANCE = new NullCustomer();
		
		private NullCustomer() {
			super("null");
		}
		
		@Override
		public boolean isNull() {
			return true;
		}
		
		private Object readResolve(){
			return INSTANCE;
		}
	}
}
Ausgabe:
Code:
null true
1 false
2 false
null true
4 false
5 false
null true
7 false
8 false
null true
Gruß Tom