Search code examples
androidalgorithmandroid-activityshopping-cart

Algorithm for quantity selection


I'm stuck with a specific problem that i want to solve.The scenario is like this for e-cart application on android

In the app the user get to choose different quantity .But the problem is that i have each item with different quantity measures and different stepping function to increase the quantity.

So how can i Simplify this.

Can any one suggest me a good algorithm to solve such problem or may be an independent solution

Thanks in advance.


Solution

  • You should have a Product class. Each product object has different quantity measures and increment methods. Something like this:

    public abstract class Product {
        String quantityMeasure; //You can encapsulate this with a getter
        public abstract int step (int value); //here you want to increment "value" with different algorithms.
    }
    

    Now you can create different product subclasses like this:

    public class FruitProduct extends Product {
        public abstract int step (int value) {
            //implementation here
        }
    
        public FruitProduct () {
            quantityMeasure = "grams";
        }
    }
    

    Now you can get the quantity measure using the Product objects.

    EDIT:

    You can also make the Product type an interface like this:

    public interface Product {
        int step(int value);
        String getQuantityMeasure();
    }
    

    Remember to implement the getQuantityMeasure method as well!

    public String getQuantityMeasure() {
        return "grams";
    }