This article presents a Super Constructor design pattern. It is equally suitable for C++ and Java.
This design pattern is applicable in cases where the constructor could return a null value or where you want to have a virtual constructor. To do this, the constructor needs to be renamed to a static method called for arguments sake: ctor. Here is the design pattern for null return values in action in the Java language:
class Foo
{
int aProperty;
private Foo(/* parameters */)
{
/* your code goes here */
}
public static Foo ctor(/* parameters */)
{
Foo returnValue = new Foo(/* arguments */);
/* set properties here */
returnValue.aProperty = 123;
/* decide whether or not to return null here */
if (/* code omitted */)
{
return returnValue;
}
else
{
return null;
}
}
}
The name ctor is used to remind the client that the method serves in the role of a constructor. The actual constructor is private so that it can only invoked indirectly by the ctor function. Here is the design pattern in action when you want to have a virtual constructor:
class Root
{
private Root(/* parameters */)
{
/* your code goes here */
}
public static Root ctor(/* parameters */)
{
if (/* code omitted */)
{
return new Root(/* arguments */);
}
else if (/* code omitted */)
{
return new SubClass(/* arguments */);
}
else
{
return null;
}
}
/* your code goes here */
}
class SubClass extends Root
{
public SubClass(/* parameters */)
{
/* your code goes here */
}
/* your code goes here */
}
Here is an alternative implementation of the Super Constructor design pattern:
class Root
{
public Root(/* parameters */)
{
/* your code goes here */
}
}
class SubClass extends Root
{
public static Root ctor(/* parameters */)
{
if (/* code omitted */)
{
return new Root(/* arguments */);
}
else if (/* code omitted */)
{
return new SubClass(/* arguments */);
}
else
{
return null;
}
}
}
Back to Research Projects |
This page has the following hit count:
|