How to use decorator pattern, when the class to decorate is final

I have an inbuilt class in java – String
Now I have made 3 classes

  1. AddHashCode
  2. ToLowerCase
  3. AddLength

I want to create a class, which has toString method overridden while selecting one or more of the above classes.

For example:
I want a class, which has toString method, which has the features of AddHashCode and ToLowerCase
or
I want a class, which has toString method, which has the features of all of the above classes.

So, lets do it with Decorator Pattern.

But the problem with Decorator Pattern is, that the classes you create must implement the String class…..But String class is final..
So I have tweaked the Decorator Design Pattern a bit, though it closely resembles the purpose of Decorator design pattern.

Create the following three classes

Class AddHashCode

public class AddHashCode {
private String t ;
public AddHashCode(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":" + t.hashCode();
}
}

Class ToLowerCase

public class ToLowerCase {
String ac;
public ToLowerCase(String ac)
{
this.ac = ac;
}
public String toString()
{
return ac.toString().toLowerCase();
}
}

Class AddLength

public class AddLength{
private String t ;
public AddLength(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":"+t.toString().length();
}
}

Use this as follows:

public class Main {
public static void main(String[] args)
{
ToLowerCase x = new ToLowerCase
(new AddHashCode
(new String("YOGESH").toString()).toString());
System.out.println(x.toString());
AddHashCode y = new AddHashCode
(new ToLowerCase
(new AddLength(new String("YOGESH").toString())
.toString())
.toString());
System.out.println(y.toString());
}
}

About Vineet Verma

Developer/Blogger/Gamer/Lazy Couch Potato...:P Need PDF Books: Knowledge Base
This entry was posted in Design Pattern. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s