Program in Java: Use the Factory pattern to address the following challenge... Y
ID: 3868724 • Letter: P
Question
Program in Java: Use the Factory pattern to address the following challenge...
Your job is to make it easy to obtain a Pet from a factory-like class:
Pet is an abstract class that has 2 attributes
Name
Sound
You should create 3 concrete types of pets
Parakeet (makes the sound "Tweet tweet")
Dog (makes the sound "Woof woof")
Lion (makes the sound "Roar roar")
You should create a factory class that allows the caller to create pets by specifying
Name
Acres of land where pets will live
The # of acres of land determines what kind of pet is assigned
1 acre or less: parakeet
4 acre or less: dog
9 acre or less: lion
Smaller pets are always preferred over larger ones
For example if the caller has 2 acres, then a new Dog should be returned.
*Your solution should minimally include 6 classes:
The abstract Pet and concrete classes (4 classes)
Factory class (1 class)
An additional Test class
Should demonstrate getting pets for the following acre sizes: 0, 3, 7
For each pet retrieved, print out its sound (to the output).
Explanation / Answer
Hello
Your required program is here.
abstract class Pet
{
String Name,Sound;
public void show();
}
class Parakeet
{
String Name,Sound;
Parakeet()
{
Name="parakeet";
Sound="Tweet tweet";
}
public void show()
{
System.out.println("Sound of Parakeet is "+Sound);
}
}
class Dog
{
String Name,Sound;
Dog()
{
Name="dog";
Sound="Woof woof";
}
public void show()
{
System.out.println("Sound of Dog is "+Sound);
}
}
class Lion
{
String Name,Sound;
Lion()
{
Name="lion";
Sound="Roar roar";
}
public void show()
{
System.out.println("Sound of Lion is "+Sound);
}
}
class Factory
{
String Name;
int acres;
public void createPets(int acres)
{
this.acres=acres;
if(acres==0)
Name="";
if(acres<=1)
Name="parakeet";
else if(1<acres<=4)
Name="dog";
else if(4<acres<=9)
Name="lion";
}
public String showName()
{
String s=Name;
return s;
}
}
class Test
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Factory f1=new Factory();
System.out.println("Enter how much acres of land:");
a=Integer.parseInt(br.readLine().trim());
f1.createPets(a);
String name=f1.showName();
if(name=="parakeet")
{
Parakeet p=new Parakeet();
p.show();
}
else if(name=="dog")
{
Dog d=new Dog();
d.show();
}
else if(name=="lion")
{
Lion l=new Lion();
l.show();
}
else //if acres=0
{
System.out.println("No pet");
}
}
}
//Hope you will give positive feedback for this
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.