dimanche 1 avril 2018

How change an object reference on run time (Design Patterns)

The application is a text based Starbucks simulator.

Image

The problem I am facing is how do I change reference to a screen base on a (x, y) values.

I am looking for a solution where I give the screen the responsibility of changing to the next screen base on x and y values.

Here is the third layer of the application which initial's screen is MyCards:

public class Frame implements IFrame {

     private IScreen current = new MyCards();

     /* Most code are taken out because not relevant */

     public void touch(int x, int y){ 
         if(current!= null){ current.touch(x, y)}

     }

}

If I call frame.touch(3,3) it should change the reference to a new screen which I call MyCardsPay.

Here is my interface I call IScreen:

public interface IScreen
{

    void touch(int x, int y) ;              // send touch events to screen
    String display() ;                      // displays screen components
    String name() ;                         // returns name of screen
    void next() ;                           // navigate to next screen
    void prev() ;                           // navigate to previous screen
    void setNext(IScreen s, String n ) ;    // set next screen with action name
    void setPrev(IScreen s, String n ) ;    // set previous screen with action name

}

Here is my base class I call Screen:

public class Screen implements IScreen {


    public Screen(){

    }

    @Override
    public void touch(int x, int y) {

    }

    @Override
    public void next() {
        // add code here

    }

    @Override
    public void prev() {
        // add code here
    }

    @Override
    public void setNext(IScreen s, String n ) {
        // add code here 
    }

    @Override
    public void setPrev(IScreen s, String n )  {
        // add code here
    }    


    @Override
    public String display() { 
        return ""; 
    }


    @Override
    public String name() {
        return (this.getClass().getName()).split("\\.")[1] ; 
    }

}

Here is my MyCard class:

public class MyCards extends Screen {

    private Double price;

    public MyCards() {

    }

    public void setPrice(Double p){
        price = p;
    }

    @Override
    public String display(){
        return getPriceDescription() + super.display();
    }

    public String getPriceDescription(){
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        return formatter.format(price);
    }
}

Here is my MyCardsPay class:

public class MyCardsPay extends Screen
{

    String cardID;

    public MyCardsPay()
    {

    }

    public void setCardID(String c){
        cardID = c;
    }

    @Override
    public String display(){
        if(cardID == null){
            return super.display();
        }
        return "[" + cardID + "]" + "\n\n\n" + "Scan Now";
    }


}

Aucun commentaire:

Enregistrer un commentaire