Artur
Artur

Reputation: 793

Return a class which is used in the method chaining

I have a following code:

class PageMedia {
    public PageMedia upload(){return this;}
    public void insert(){}
}

class PageA {    
    public PageA dosomething(){ return this;}
    public void openMedia(){ return page(PageMedia.class);}
    public PageA save(){ return this;}

}

class PageB {   
    public PageB dosomething(){ return this;}
    public void openMedia(){ return page(PageMedia.class);}
    public PageB save(){ return this;}
}

Each class is unique and each method is unique.
It is needed that method "insert" of class PageMedia returns a class PageA or PageB, which is used in the chain.

So it would be possible to do following:

PageA.open()
    .dosomething()
    .openMedia()
    .upload()
    .insert()
    .save;

PageB.open()
    .dosomething()
    .openMedia()
    .upload()
    .insert()
    .save;

Upvotes: 0

Views: 94

Answers (2)

WiPU
WiPU

Reputation: 443

If i understand your questions right. You can use something like this:

interface Page {
    //general Methods ... save, openMedia, ...
}

class PageMedia {

    Page reference;

    public PageMedia(Page reference){
        this.refreence = reference;
    }

    public PageMedia upload(){return this;}
    public Page insert(){ return reference;}
}

class PageA implements Page{    
    public PageA dosomething(){ return this;}
    public PageMedia openMedia(){ return new PageMedia(this);}
    public Page save(){ return this;}

}

regards, WiPu

Upvotes: 2

H3llskrieg
H3llskrieg

Reputation: 94

you would need to make an interface which is implemented by both PageA and PageB and return an an object that is of a class implementing that interface. Depend on abstractions, not implementations.

You should get something like this:

interface IPage {IPage doSomething(); }
public IPage insert() {return new PageA()}
class PageA implementes IPage
class PageB implementes IPage

Upvotes: 1

Related Questions