State of object
I wanted to create Items and be able to display it. The user will do some selection based on what i had displayed. But the constraint was when am asked to add new items i should do it without modifying existing code. I thought factory pattern would solve the issue. I was able to create a facotry which would create instance of an item. This works fine, but the problem is how do i save the state of the object. Like if i have two items. i would want to have object1 with its name, price and manufacturer and object with its details like wise.
I want this because I should be able to display the items somewhere else.
Item.java
public class Item {
int _price;
String _nameOfItem;
String _manufacturer;
int count = 0 ;
public Item() {
}
public void setname(String nameOfItem){
_nameOfItem = nameOfItem;
System.out.println("name of appliance: " +_nameOfItem);
}
public void getprice() {
System.out.println("price: " +_price);
}
public void setprice(int price) {
_price = price;
}
public void setmaker(String maker) {
_manufacturer = maker;
}
public void getmaker(){
System.out.println("manufacured by: " + _manufacturer);
}
}
ItemFactory.java
public class ItemFactory {
Item i;
public void getObject(String str,String name,int cost,String manufacturer) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class c = Class.forName(str);
Item i = (Item)c.newInstance();
setDetails(i,name,cost,manufacturer);
}
public void setDetails(Item i,String name,int cost,String maker){
i.setname(name);
i.setprice(cost);
i.getprice();
i.setmaker(maker);
i.getmaker();
}
client.java
public class Client {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
ItemFactory i = new ItemFactory();
i.getObject("Item","Microwave",1222,"LG");
//i.getObject("Item","Fan",2233,"kaitan");
//i.getObject("Item","fridge",1234,"LG");
}
}
I might be be wrong in how i went about coding this.
but any help would be reallly appreciated
Thanks
k

