Very Simple Use of decorator pattern to generate numbers

decorator, java

Solution

First the decorator class does not have to extend the class that decorates but implements the same interface.

Look at this Wikipedia page.

So you can correct your decorator like this:

// The interface
public interface NextNumber {

     public int getNextNumber();
}

// The class to decorate
public class PrintNumbers implements NextNumber {

    protected int num;

    public PrintNumbers(int startFrom)
    {
        this.num = startFrom;
    }

    public int getNextNumber()
    {
        return num++;
    }
}

// The abstract decorator
public abstract class DecoratorCount implements NextNumber {

    private PrintNumbers pn;

    public DecoratorCount(PrintNumbers pn)
    {
       this.pn = pn;
    }
}

Then for example you can multiply number by 2.

public class DoubleDecoratorCount extends DecoratorCount {

    public DecoratorCount(PrintNumbers pn)
    {
        super(pn);
    }

    public int getNextNumber()
    {    
        return pn.getNextNumber() * 2;
    }
}

And you can test decorator in this way

public class Test {

    public static void main (String[] args) {
        PrintNumbers pn = new PrintNumbers(0);
        DoubleDecoratorCount decorator = new DoubleDecoratorCount(pn);
        for (int i = 0 ; i < 5 ; ++i)
            System.out.println("value: " + decorator.getNextNumber());
    }
}

At this point you can write all decorators you need:

- To multiply by 3;

- To write results in letter;

- To write results in hex;

- Etc...

Problem

I am new to design patterns and I was asked to print numbers from 1 to 10 using decorator pattern. I am sorry if this is trivial but I need to learn. This is what I have so far: Interface ``` public interface NextNumber { public int getNextNumber(int n); } ``` Abstract Class ``` abstract public class PrintNumbers implements NextNumber { protected final NextNumber next; protected int num; public PrintNumbers(NextNumber next, int num) { this.next = next; this.num = num; } public int getNextNumber(int num) { return num+1; } } ``` DecoratorClass ``` public class DecoratorCount extends PrintNumbers { public DecoratorCount(NextNumber next, int num) { super(next, num); } public static void main(String[] args) { int i = 0; } } ``` Not sure how to proceed or even if I am going the right way. Could someone shed some light?

Original source