Kody źródłowe/Pusty Obiekt (wzorzec projektowy)
Java
edytuj/** AbstractObject */
public interface Shape2D {
void move(double x, double y);
}
/** RealObject */
public class Circle implements Shape2D {
@Override
public void move(double x, double y) {
System.out.println("Shape has been moved by vector(" + x + "," + y + ")");
}
}
/** NullObject */
public class NullShape2D implements Shape2D {
@Override
public void move(double x, double y) {
// do nothing
}
}
/** Client program */
public class NullObjectExample {
public static void main(String[] args) {
Shape2D[] shapes = { new NullShape2D(), new Circle(), new NullShape2D(), new Circle() };
/* zamiast za każdym razem sprawdzać warunek, czy referencja posiada wartość pustą
*for (int i = 0; i < shapes.length; i++) {
* if (shapes[i] != null) {
* shapes[i].move(i, i);
* }
*}
* Stosuje się wzorzec Pusty Obiekt
*/
for (int i = 0; i < shapes.length; i++) {
shapes[i].move(i, i);
}
}
}
C#
edytujusing System;
/** AbstractObject */
interface IAnimal
{
void MakeSound();
}
/** RealObject */
class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Woof!");
}
}
/** NullObject */
class NullAnimal : IAnimal
{
public void MakeSound()
{
// Purposefully provides no behaviour.
}
}
/** Client program */
static class Program
{
static void Main()
{
IAnimal dog = new Dog();
dog.MakeSound(); // outputs "Woof!"
/* Instead of using C# null, use a NullAnimal instance.
* This example is simplistic but conveys the idea that if a NullAnimal instance is used then the program
* will never experience a .NET System.NullReferenceException at runtime, unlike if C# null was used.
*/
IAnimal unknown = new NullAnimal(); //<< replaces: IAnimal unknown = null;
unknown.MakeSound(); // outputs nothing, but does not throw a runtime exception
}
}