decorator pattern example in java

This is a simple java exercise about decorator pattern and how to implement Decorator Pattern 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.

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 on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment