Monday, July 7, 2014

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());
	}
}

No comments:

Post a Comment