Friday 24 October 2014

decorator pattern example in java

Structure of the Problem Requirements 

In this problem we will learn about decorator pattern and how the  Decorator Pattern is implemented in Java.? Take a string and apply different decorator on it. All methods are implemented in Printer class. Decorator pattern allows to add new functionality with an existing object without changing any state of that object. Here is the source code of this problem which help you in better  understanding.



SOURCE CODE 





public class DecoratorDriver {
    public static void main(String args[]){
        Printer pr = new SimplePrinter();
        pr = new BulletDecorator(pr);
        pr = new BorderDecorator((pr));
        String st = "Check List for Exam Prep. Get Lecture Notes. Get Software Tools. Arrange Group Study. Arrange Edible. Have a good Night Sleep";
        System.out.println(pr.getOutput(st));
     
    }
}

//printer class


public abstract class Printer {
    public abstract String getOutput(String input);

}
class SimplePrinter extends Printer{
    public String getOutput(String input){
        return input+".";
    }
}

abstract class PrinterDecorator extends Printer{
    protected Printer p;
    public PrinterDecorator(Printer pp){
        p = pp;
    }

}
class BulletDecorator extends PrinterDecorator{
    public BulletDecorator(Printer p){
        super(p);
    }

    public String getOutput(String input){
        String in = p.getOutput(input);
        int lnl = in.lastIndexOf(".");
        int fln = in.indexOf(".");
        int ln = 1;
        int i = fln;
        String out = ln++ + "-->  "+in.substring(0, fln) + "\n";
         i = in.indexOf('.', fln+1);
        while(i<lnl){
            int inew = in.indexOf('.',i+1);
            out = out+ln++ + "-->  "+in.substring(i+1,inew ) + "\n";
            i = inew;

        }
         return out;
    }
}
class BorderDecorator extends PrinterDecorator{
    public BorderDecorator(Printer p){
        super(p);
    }
    public String getOutput(String input){
       
        int i = 0;
        String in = p.getOutput(input);
        String bout = "***********************************************************\n";
        String out = bout +  in + "\n" +bout;
        return out;
    }
}

OUTPUT OF THE PROGRAM


Decorator Design Pattern in Java
Decorator Design Pattern in Java



Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment