You are on page 1of 2

import java.util.

ArrayList;
public class Selection2 {
public static void main(String args[]) {
Product pl = new Product("beef", 5);
Product p2 = new Product("milk", 2);
Product p3 = new Product("ziti", 8);
Product p4 = new Product("cheese", 3);
MyContext ctx = new MyContext();
ctx.addProduct(p1);
ctx.addProduct(p2);
ctx.addProduct(p3);
ctx.addProduct(p4);
ctx.setWorker(new NameWorker());
ctx.showProductsInPriceRange (2, 5);
ctx.setWorker(new PriceWorker());
ctx.showProductsInPriceRange (3, 8);
}
}

class Product {
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}

public String getName() { return name; }


public int getPrice() { return price; }
}

class MyContext {

private Worker imp;


private ArrayList<Product> plist = new ArrayList<Product>();

public void setWorker (Worker s) { imp = s; }

public void showProductsInPriceRange(int lower, int upper) {


ArrayList<Product> filteredList = new ArrayList<Product>();
for (Product p : plist) {
if ((p.getPrice() >= lower) && (p.getPrice() <= upper))
filteredList.add(p);
}
ArrayList<Product> mList = imp.update(filteredList);
for (Product p mList) {
System.out.println(p.getName() + p.getPrice() );
}
}
public void addProduct (Product p) { plist.add(p); }

abstract class Worker {


public abstract ArrayList<Product> update(ArrayList<Product> q);
}

class NameWorker extends Worker {


public ArrayList<Product> update(ArrayList<Product> q) {
ArrayList<Product> cloned = (ArrayList<Product>)q.clone();
ArrayList<Product> updated = new ArrayList<Product>();
for (int i = 0; i < q.size(); i++) {
Product m = cloned.get(0);
for (int j = 0; j < cloned.size(); j++) {
Product p = cloned.get(j);
if (m.getName().compareTo(p.getName()) > 0) {
m = p;
}
}
updated.add(m);
cloned.remove(m);
}
return updated;
}
}

class PriceWorker extends Worker {


public ArrayList<Product> update(ArrayList<Product> q) {
ArrayList<Product> cloned = (ArrayList<Product>)q.clone();
ArrayList<Product> updated = new ArrayList<Product>();
for (int i = 0; i < q.size(); i++) {
Product m = cloned.get(0);
for (int j = 0; j < cloned.size(); j++) {
Product p = cloned.get(j);
if (m.getPrice() < p.getPrice()) {
m = p;
}
}
updated.add(m);
cloned.remove(m);
}
return updated;
}
}

You might also like